I. How to use Java for database operations:
1. Load the appropriate driver according to the database type of the application;
2. Connect to the database and get the connection object;
3. Create statement objects through connection;
4. Submit the SQL statement using the statement object;
5. Operation Result set
6. Reclaim Database Resources
7. Close the connection
PackageCom.lovo.jdbc;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.SQLException;Importjava.sql.Statement; Public classJDBCTESTDML { Public Static voidMain (string[] args) {//database operation steps://1. Load driver--tell the driver Manager which database drive package we will use Try { //url--Uniform Resource Locator----style: protocol://IP Address: port number/serviceClass.forName ("Com.mysql.jdbc.Driver"); } Catch(ClassNotFoundException e) {e.printstacktrace (); } //2. Operation of JDBC API to complete database action//①, getting connectionsConnection con =NULL; Try { //usessl=false--means not to display a security warning? useunicode=true&characterencoding=utf8--appear garbled when changed to their own consistent code, such as utf-8dcon = drivermanager.getconnection ("Jdbc:mysql://127.0.0.1:3306/test134?usessl=false", "root", "13405"); //②-1, writing SQL statements------string concatenation,//Increase//String sql= "INSERT into T_class (f_classname,f_teacher) VALUES (' j22 ', ' curved ')"; //ChangeString sql= "UPDATE t_class SET f_classname = ' j66 ', f_teacher= ' very low ' WHERE Pk_classsid = 4"; //②-2, gets the statement object-----statement to the imageStatement State =con.createstatement (); //②-3, executes the statement object------All DML statements, executes the executeupdate () method all introw=state.executeupdate (SQL); } Catch(SQLException e) {e.printstacktrace (); }finally { //③, close connection if(con!=NULL){ Try{con.close (); } Catch(SQLException e) {e.printstacktrace (); } } } }}
The above example uses DML statements only additions and deletions, so there is no return of the result set, when using the DQL statement query, there will be a result set of the appearance and use.
Java database Programming (JDBC)