JDBC connects to the database
The main steps for JDBC to connect to the database are as follows:
1. Load the JDBC driver
Class.forName ("com.mysql.jdbc.Driver")
After loading successfully, an instance of the Driver class is registered with the DriverManager class.
2. Provide URL to connect to JDBC
URL=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk
UseUnicode=true&characterEncoding=gbk sets database encoding
3. Create a database connection
To connect to a database, you need to request a java.sql.DriverManager and get a Connection object, which represents a connection to a database.
String username= "root"; String password= "123456"; Connection conn=DriverManager.getConnection (URL,username,password)
4. Create a statement
To execute a SQL statement, you must obtain a java.sql.Statement instance. Common Statement instances are
(1) execute static SQL statements, usually through Statement instances
Statement st=conn.createStatement ()
(2) execute dynamic SQL statements, usually through PreparedStatement instances
String sql= "select * from tablename"; PreparedStatement ps=conn.perpareStatement (sql)
5. Execute the SQL statement
The Statement interface provides three ways to execute SQL statements: executeQuery,executeUpdate,execute
String sql= "select * from test"; String sql2= "insert into book" ("bookName", "price", "author"publish") values ("Java Technology", 99.999," Jhon "," Tsinghua University Press ")
① executeQuery (String sql): executes a query database statement that returns a result set ResultSet object
ResultSet rs=st.executeQuery (sql)
② executeUpdate (String sql): executes INSERT,UPDATE or DELETE statements and SQL DDL statements
Int rows=st.executeUpdate (sql2)
③ execute (String sql): used to execute statements that return multiple result sets, multiple update techniques, or combinations.
Boolean flag=st.execute (String sql)
6. Processing result
(1) the number of records affected by this operation is returned by performing the update.
(2) the result returned by executing the query is a ResultSet object.
While (rs.next ()) {string author=rs.getString (3); / / from left to right, index starts at 1}
7. Close the JDBC object
Close the recordset, close the declaration, and close the connection object.
If (rsgiving null) {rs.close ();} if (stalled null) {st.close ();} if (connate null) {conn.close;}