Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import Java.util.Date;
Import Org.junit.Test;
Public class Test {br/> @Test
PreparedStatement preparestatement = null;
Connection Connection = null;
try {
//1. Load driver
Class.forName ("Com.mysql.jdbc.Driver");
2. Get the link
connection = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/test", "root", "root");
3. Write SQL statement
String sql = "INSERT into product values (null,?,?,?)";
//4. Precompiled
Preparestatement = connection.preparestatement (sql);
5. Set the Parameters
Preparestatement.setstring (1, "Apple");
Preparestatement.setdouble (2, 3.5);
Preparestatement.setobject (3, New Date ());
//6. Execute
preparestatement.executeupdate ();
} catch (ClassNotFoundException | SQLException e) {//TODO auto-generated catch block E.printstacktrace (); }finally {//7. Close capital try {if (preparestatement!=null) {preparestatement.close (); } if (Connection!=null) {connection.close (); }} catch (SQLException e) {e.printstacktrace (); }}} @Testpublic void Testjdbcselect () {PreparedStatement preparestatement = null; Connection Connection = null; ResultSet executeQuery = null; try {//1. Load driver Class.forName ("Com.mysql.jdbc.Driver"); 2. Get Link connection = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/test", "root", "root"); 3. Write SQL statement String sql = "SELECT * from product where pid=?"; 4. Precompiled preparestatement = connection.preparestatement (sql); 5. Set the parameter Preparestatement.setint (1, 1); 6. Execute executeQuery = PreParestatement.executequery (); while (Executequery.next ()) {System.out.println (Executequery.getint (1)); System.out.println (executequery.getstring (2)); System.out.println (Executequery.getdouble (3)); System.out.println (Executequery.getdate (4)); }} catch (ClassNotFoundException | SQLException e) {e.printstacktrace (); }finally {//7. Close capital try {if (executequery!=null) {executequery.close (); } if (Preparestatement!=null) {preparestatement.close (); } if (Connection!=null) {connection.close (); }} catch (SQLException e) {e.printstacktrace (); } }}
}
/*
Note that the JDBC modification Delete addition is similar to the SQL statement, so this is just a write to add
Precompiling not only improves performance but also prevents SQL injection
*/
JDBC Link MySQL