To connect to a database step:
A. Using a Java program to establish a connection (channel) with a DB
B. Gets an object that executes an SQL statement based on the connection
C. Execute SQL statement
D. Close connection
public class Main {
public static void Main (string[] args) {
try {
1 Loading the driver class
Forname () Returns the class object associated with the classes or interfaces with the given string name
Class.forName ("Org.gjt.mm.mysql.Driver");
A. Establishing a connection channel
DriverManager manages a set of basic services for a JDBC driver. java.sql
Getconnection () Return: Connection to URL
String url= "Jdbc:mysql://127.0.0.1:3306/a11";
String user= "root";
String password= "root";
Connection conn=drivermanager.getconnection (URL, user,password);
B. Gets an object that executes the SQL statement
The Statement is used to execute a static SQL statement and return the object to which it produces results.
Createstatement () Creates a Statement object to send the SQL statement to the database.
Statement St;
St=conn.createstatement ();
C. Executing SQL statements
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement, or do not return content
St.executeupdate ("INSERT into student (Stuname,stuage,stusex,stubirth) VALUES (' Zhang San ', ' Ten, ' m ', ' 1988-08-09 ')");
D. Closing the connection
Immediately frees the database and JDBC resources for this Connection object, rather than waiting for them to be freed automatically
Conn.close ();
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
SYSTEM.OUT.PRINTLN ("Load Driver class failed!") ");
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
or close write in finally
Java Connection JDBC Section