Mysql 12: JDBC connection to the database DriverManager method _ MySQL

Source: Internet
Author: User
Mysql 12: The DriverManager method for connecting to the database through JDBC
  1. Connect to the database through JDBC
  2. Create a program to connect to the database using JDBC, which contains seven steps:
  3. 1. load the JDBC driver:
  4. Before connecting to the database, load the driver of the database to be connected to the JVM (Java virtual machine ),
  5. This is achieved through the static method forName (String className) of the java. lang. Class.
  6. For example:
  7. Try {
  8. // Load the MySql driver class
  9. Class. forName ("com. mysql. jdbc. Driver ");
  10. } Catch (ClassNotFoundException e ){
  11. System. out. println ("The driver class cannot be found. failed to load the driver! ");
  12. E. printStackTrace ();
  13. }
  14. After the Driver class is loaded, the Driver class instance is registered to the DriverManager class.
  15. 2. provide the URL of the JDBC connection
  16. The connection URL defines the protocol, sub-protocol, and data source identification used to connect to the database.
  17. Writing format: Protocol: Sub-protocol: Data Source ID
  18. Protocol: always starts with JDBC in jdbc.
  19. Sub-protocol: the name of the bridge connection driver or database management system.
  20. Data Source ID: Mark the address and connection port of the database source.
  21. Example: (MySql connection URL)
  22. Jdbc: mysql:
  23. // Localhost: 3306/test? UseUnicode = true & characterEncoding = gbk;
  24. UseUnicode = true: indicates that the Unicode character set is used. If characterEncoding is set
  25. Gb2312 or GBK. this parameter must be set to true. CharacterEncoding = gbk: Character encoding method.
  26. 3. create a database connection
  27. To connect to the database, you must request to java. SQL. DriverManager and obtain the Connection object,
  28. This object represents a database connection.
  29. Use getConnectin (String url, String username,
  30. String password ).
  31. Password.
  32. For example:
  33. // Connect to the MySql database. both the user name and password are root.
  34. String url = "jdbc: mysql: // localhost: 3306/test ";
  35. String username = "root ";
  36. String password = "root ";
  37. Try {
  38. Connection con =
  39. DriverManager. getConnection (url, username, password );
  40. } Catch (SQLException se ){
  41. System. out. println ("database connection failed! ");
  42. Se. printStackTrace ();
  43. }
  44. 4. create a Statement
  45. To execute an SQL Statement, you must obtain the java. SQL. Statement instance. the Statement instance is divided into three types:
  46. Type:
  47. 1. execute static SQL statements. It is usually implemented through a Statement instance.
  48. 2. execute dynamic SQL statements. It is usually implemented through the PreparedStatement instance.
  49. 3. execute the database stored procedure. It is usually implemented through the CallableStatement instance.
  50. Specific Implementation methods:
  51. Statement stmt = con. createStatement ();
  52. PreparedStatement pstmt = con. prepareStatement (SQL );
  53. CallableStatement cstmt =
  54. Con. prepareCall ("{CALL demoSp (? ,?)} ");
  55. 5. execute SQL statements
  56. The Statement interface provides three methods for executing SQL statements: executeQuery and executeUpdate.
  57. And execute
  58. 1. ResultSet executeQuery (String sqlString): Run the SQL statement used to query the database.
  59. Returns a result set object.
  60. 2. int executeUpdate (String sqlString): used to execute INSERT, UPDATE, or
  61. DELETE statements and SQL DDL statements, such as CREATE TABLE and DROP TABLE
  62. 3. execute (sqlString): used for executing and returning multiple result sets, multiple update counts, or a combination
  63. Statement.
  64. Specific implementation code:
  65. ResultSet rs = stmt.exe cuteQuery ("SELECT * FROM ...");
  66. Int rows = stmt.exe cuteUpdate ("insert ...");
  67. Boolean flag = stmt.exe cute (String SQL );
  68. 6. processing result
  69. Two cases:
  70. 1. the number of records affected by this operation is returned when an update is executed.
  71. 2. the result returned by executing the query is a ResultSet object.
  72. The ResultSet contains all rows that meet the conditions in the SQL statement, and provides
  73. The data in the row.
  74. Use the access method of the result set object to obtain data:
  75. While (rs. next ()){
  76. String name = rs. getString ("name ");
  77. String pass = rs. getString (1); // This method is more efficient.
  78. }
  79. (Columns are numbered from left to right and start from column 1)
  80. 7. disable JDBC objects
  81. After the operation is completed, all the used JDBC objects should be closed to release the JDBC resources, close the sequence and
  82. Reverse order:
  83. 1. disable record set
  84. 2. close the statement
  85. 3. close the connection object
  86. If (rs! = Null) {// close the record set
  87. Try {
  88. Rs. close ();
  89. } Catch (SQLException e ){
  90. E. printStackTrace ();
  91. }
  92. }
  93. If (stmt! = Null) {// Close the declaration
  94. Try {
  95. Stmt. close ();
  96. } Catch (SQLException e ){
  97. E. printStackTrace ();
  98. }
  99. }
  100. If (conn! = Null) {// close the connection object
  101. Try {
  102. Conn. close ();
  103. } Catch (SQLException e ){
  104. E. printStackTrace ();
  105. }
  106. }

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.