Operation Steps:
1. Load the database driver (first in the project to download the corresponding driver package for the database)
2. Get the connection
3. Create an executable SQL object based on the connection
4. Execute SQL statements
5. Close the connection
Code:
Packagedatabase;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public classMysqltest { Public Static voidMain (string[] args) {Connection conn=NULL; Statement stmt=NULL; ResultSet RS=NULL; Try{//Load DriverClass.forName ("Com.mysql.jdbc.Driver"); } Catch(ClassNotFoundException e) {e.printstacktrace (); } Try{//Get connection jdbc:mysql://This paragraph is a fixed format, localhost is the server address, 3306 is the port, server installation configuration, root is the user name, write dead, password is installed when the server configuration. conn = Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/mydata", "Root", "" "); } Catch(SQLException e) {e.printstacktrace (); } Try{//gets an object that executes an SQL statement based on the connectionstmt =conn.createstatement (); } Catch(SQLException e) {e.printstacktrace (); } Try{//Execute SQL statementrs = Stmt.executequery ("SELECT * FROM dept"); } Catch(SQLException e) {e.printstacktrace (); } Try{//Print the contents of the table, subscript starting from 1 while(Rs.next ()) {System.out.print (rs.getstring (1) + ""); System.out.print (Rs.getstring (2) + ""); System.out.print (Rs.getstring (3)); System.out.println (); } } Catch(SQLException e) {e.printstacktrace (); } Try{//Close ConnectionConn.close (); } Catch(SQLException e) {e.printstacktrace (); } }}
Connection operation and shutdown for MySQL data