Java程序调用MySQL数据库实例代码

2014-11-23 23:31:31 · 作者: · 浏览: 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. public class MySQLTest {
  6. public static void main(String[] args) {
  7. // TODO Auto-generated method stub
  8. Connection conn = null;
  9. try
  10. {
  11. String userName = "username";
  12. String password = "password";
  13. String url = "jdbc:mysql://localhost/test";
  14. Class.forName ("com.mysql.jdbc.Driver").newInstance ();
  15. conn = DriverManager.getConnection (url, userName, password);
  16. System.out.println ("Database connection established");
  17. PreparedStatement pstmt;
  18. ResultSet rset;
  19. pstmt = conn.prepareStatement("select count(*) from testtable");
  20. rset=pstmt.executeQuery();
  21. while (rset.next()){
  22. System.out.println (rset.getString(1)); // Print col 1
  23. }
  24. }
  25. catch (Exception e)
  26. {
  27. System.err.println ("Cannot connect to database server");
  28. }
  29. finally
  30. {
  31. if (conn != null)
  32. {
  33. try
  34. {
  35. conn.close ();
  36. System.out.println ("Database connection terminated");
  37. }
  38. catch (Exception e) { /* ignore close errors */ }
  39. }
  40. }
  41. }
  42. }