9 Steps:
1, load the database driver;
2, connect the database;
3, create statement;
5, create SQL syntax string;
6, implementation;
7, if step 6 is to perform new, modify, delete operation then return the number of rows affected, if you are performing a query operation, then step 8:
8, analytic result set resultset;
9. Close the result set resultset, close the statement, and close the database connection.
On the code:
Public Static voidMain (string[] args)throwsSQLException {Try{class.forname ("Com.mysql.jdbc.Driver"); } Catch(ClassNotFoundException e) {System.out.println ("Driver class not found!" "); E.printstacktrace (); } String URL= "Jdbc:mysql://localhost:3306/exe_course"; String UserName= "Root"; String Password= "123456"; Try(Connection Connection =drivermanager.getconnection (URL, userName, password)) {System.out.println ("The database link was successful!" "); Try(Statement Statement =connection.createstatement ()) {String command= "INSERT into a_dept (name) VALUES (' 1 '), (' 2 ')"; intCount =statement.executeupdate (command); System.out.println (Number of affected rows: +count); String Selectsql= "SELECT * FROM A_dept"; Try(ResultSet ResultSet =statement.executequery (Selectsql)) { while(Resultset.next ()) {System.out.println (Resultset.getint ("id")); System.out.println (Resultset.getstring ("Name")); } } } } }
The above code uses two usages of try, and it is recommended to use the second usage when you need to release resources, which automatically shuts down resources after the end of use.
Here is the result of the operation:
Java Database connection and query