Java program calls the MySQL database instance code

Source: Internet
Author: User

  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. Rsetaskpstmt.exe cuteQuery ();
  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. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.