Created
January 13, 2016 18:06
-
-
Save Cartman0/686804811aa39d6610a9 to your computer and use it in GitHub Desktop.
access MySQL DB by DAO pattern, print "name" of colum.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sampledao; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.PreparedStatement; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
/** | |
* access MySQL DB by DAO pattern, print "name" of colum. | |
* @author cartman | |
*/ | |
public class SampleDao { | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
// TODO code application logic here | |
Connection connection = null; | |
PreparedStatement pre_statement = null; | |
ResultSet result_set = null; | |
try { | |
// mySQLの接続 | |
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample?useUnicode=true&characterEncoding=utf8", "user_name", "password"); | |
pre_statement = connection.prepareStatement("select * from user"); | |
result_set = pre_statement.executeQuery(); | |
while (result_set.next()) { | |
System.out.println(result_set.getString("name")); | |
} | |
} catch (SQLException sqle) { | |
sqle.printStackTrace(); | |
} finally { | |
closeSql(connection, pre_statement, result_set); | |
} | |
} | |
static void closeSql(Connection con, PreparedStatement ps, ResultSet rs) { | |
try { | |
if (con != null) { | |
con.close(); | |
} | |
if (ps != null) { | |
ps.close(); | |
} | |
if (rs != null) { | |
rs.close(); | |
} | |
} catch (SQLException sqle) { | |
System.err.println("Error closeSql Func"); | |
sqle.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment