Advertisement
Guest User

Untitled

a guest
Jan 13th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. package sampledao;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8.  
  9. /**
  10. * access MySQL DB by DAO pattern, print "name" of colum.
  11. * @author cartman
  12. */
  13. public class SampleDao {
  14.  
  15. /**
  16. * @param args the command line arguments
  17. */
  18. public static void main(String[] args) {
  19. // TODO code application logic here
  20. Connection connection = null;
  21. PreparedStatement pre_statement = null;
  22. ResultSet result_set = null;
  23.  
  24. try {
  25. // mySQLの接続
  26. connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample?useUnicode=true&characterEncoding=utf8", "user_name", "password");
  27.  
  28. pre_statement = connection.prepareStatement("select * from user");
  29. result_set = pre_statement.executeQuery();
  30.  
  31. while (result_set.next()) {
  32. System.out.println(result_set.getString("name"));
  33. }
  34.  
  35. } catch (SQLException sqle) {
  36. sqle.printStackTrace();
  37. } finally {
  38. closeSql(connection, pre_statement, result_set);
  39. }
  40. }
  41.  
  42. static void closeSql(Connection con, PreparedStatement ps, ResultSet rs) {
  43. try {
  44. if (con != null) {
  45. con.close();
  46. }
  47. if (ps != null) {
  48. ps.close();
  49. }
  50. if (rs != null) {
  51. rs.close();
  52. }
  53. } catch (SQLException sqle) {
  54. System.err.println("Error closeSql Func");
  55. sqle.printStackTrace();
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement