How does JDBC access the MySQL database, and add, delete, check and modify

Import the driver package and load the specific driver class

Guide package:

  • Create a new Java Project file, and create a new Folder file named lib in this folder (some imported packages are placed in this folder)
  • Drag mysql-connector-java-xxxx.jar in, right-click Build Path→Add to Build Path; (here I use mysql-connector-java-8.0.20.jar)

Load a specific driver class:

Class.forName("com.mysql.cj.jdbc.Driver");

Establish a connection with the database connection

String url = "jdbc:mysql://localhost:3306/****?serverTimezone=UTC";
//****是你要访问的数据库是哪个,mysql版本5.0以上需要在后面加上serverTimezone=UTC
//String url = "jdbc:mysql://localhost:3306/****?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"; 

String username = "****"; //数据库的用户名
String password = "****";//数据库的密码

Connection con = DriverManager.getConnection(url, username, password);

Send sql statement, execute sql statement (Statement)

Add, delete and modify operations:

Statement statement = connection.createStatement();

String sql = "insert into user values(1,'Jackage','857857')";//插入一条数据

int executeUpdate = statement.executeUpdate(sql);//返回值表示改动了几条数据

Query operation:

String sql = "select name,password from user";<em>//查询数据</em>

ResultSet rs = statement.executeQuery(sql);

Processing the result set (query)

Processing the results of additions, deletions and modifications:

if (executeUpdate > 0) {
  System.out.println("操作成功!!!");
} else {
  System.out.println("未发生改动!!!!");
}

Processing the results of the query:

while (rs.next()) {
	String uname = rs.getString("name");
	String upwd = rs.getString("password");
	System.out.println(uname+ "  " + upwd);
}

The above are the simple steps for JDBC to access the database, we also need to throw an exception in the middle

Except Class.forName() throws ClassNotFoundException, all other methods throw SQLException

Finally, you need to close connection, statement, rs

The order of closing is opposite to the order of opening, and an exception must be thrown at the same time

try {
 if(rs!=null)rs.close()
 if(stmt!=null) stmt.close();
 if(connection!=null)connection.close();
} catch (SQLException e) {
	e.printStackTrace();
}

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113615533