java JDBC connection mysql

Preparation conditions:

1. JDBC jar package ( available here )

2, wampserver is used as a server

Process:

1. To load the driver, first import the jar package before loading, create a new lib folder under the project directory, put the jar package in lib, and then import the jar package into the project, which will not be described in detail. Use the Class.forName method to load the driver.

2. Connecting to the database is basically a fixed format. In the middle, it is necessary to explain what database to connect to, server address, port number, database name, user name, and password.

3. An object is output to indicate that the connection is successful.

4. Execute a query statement, save it to a data object, and then obtain the data according to the column properties of the database.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class Main {
	 public static void main(String[] args) throws ClassNotFoundException, SQLException {
	  //1 load the driver
	  Class.forName("com.mysql.jdbc.Driver");
	     //2 Get the connection to the database
	  Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "");
	  System.out.println(con);
	  //3
	  String sql = "select * from student";
	  PreparedStatement pst = con.prepareStatement(sql);    
 	  ResultSet rst = pst.executeQuery(); //The method of executing the query statement returns an array similar to
 	  while(rst.next()){
 		  int id = rst.getInt("id ");
 		  String name = rst.getString("name");
 		  int age = rst.getInt("age");
 		  System.out.println(id+"---"+name+"---"+age);
 	  }
 	  rst.close();
 	  pst.close();
 	  con.close();
	 
	 }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324672457&siteId=291194637