MySQL database for JAVA learning

Table of contents

1. Java to connect to the database

2. Load the driver

3. Connect and close the database

4. Database query operation

5. Database addition operation

6. Database modification operation

7. Database delete operation


JAVA connection database

1. Import the jar package

1. Select the project, right click, Build Path, Confiqure Build Path

 2. Select Libearies, after selecting Modulepath, the button on the right becomes selectable, select Add External JARs, find the jar package connected to Java in the MySQL installation package, double-click it to look like the picture below, select Apply and Close in the lower right corner

2. Load the driver

Write the code as follows, if there is no error after running, it proves that the database driver has been configured successfully

package test;
import java.sql.*;
public class Main {
	//定义MySQL的数据库驱动程序
	public static final String DBC="com.mysql.cj.jdbc.Driver";

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			//加载驱动程序
			Class.forName(DBC);
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}

Note: Sometimes the following error occurs during configuration: java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

There may be a problem with the CLASSPATH setting, or it may be caused by the command line mode not being restarted

3. Connect and close the database

code show as below:

Note: The database must be closed after it is opened. The resources of the database are very limited in the operation of the program, which requires the developer to close it after operating the database. If this is not done, it may fail during the program operation. Exception connecting to database

package test;
import java.sql.*;
public class Main {
	//定义MySQL的数据库驱动程序
	public static final String DBC="com.mysql.cj.jdbc.Driver";
	//定义MySQL数据库的连接地址,user为数据库名
	 static final String DB_URL = "jdbc:mysql://localhost:3306/user";
	 //数据库的用户名
	  static final String USER = "root";
	 //数据库的密码
	  static final String PASS = "123456";
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//数据库连接
		Connection conn=null;   
		try {
			//加载驱动程序
			Class.forName(DBC);
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			//连接数据库
			 conn = DriverManager.getConnection(DB_URL,USER,PASS);
		}catch(SQLException e){
			e.printStackTrace();
		}
		System.out.println(conn);
		try {
			conn.close();
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}

}

The running results are as follows: the running result of the program is not empty, indicating that the database has been successfully connected at this time

4. Database query operation

Use Navicat to connect to the database, and follow-up operations are carried out in it

First create a database user, create a new table information, including two fields name and password, store some data in it, and use eclipse to query.

The code of the query operation is as follows, which can be modified on the basis of the connection operation

package test;
import java.sql.*;
public class Main {
	//定义MySQL的数据库驱动程序
	public static final String DBC="com.mysql.cj.jdbc.Driver";
	//定义MySQL数据库的连接地址,user为数据库名
	 static final String DB_URL = "jdbc:mysql://localhost:3306/user";
	 //数据库的用户名
	  static final String USER = "root";
	 //数据库的密码
	  static final String PASS = "123456";
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	      Connection conn = null;//数据库连接
	        Statement stmt = null;//数据库操作
	        try{
	            // 注册 JDBC 驱动
	            Class.forName(DBC);

	            // 打开链接
	     
	            conn = DriverManager.getConnection(DB_URL,USER,PASS);

	            // 执行查询
	            stmt = conn.createStatement();
	            String sql;
	            sql = "SELECT  name, password FROM information";
	            ResultSet rs = stmt.executeQuery(sql);

	            // 展开结果集数据库
	            while(rs.next()){
	                // 通过字段检索
	               
	                String name = rs.getString("name");
	                String password = rs.getString("password");
	               
	                // 输出数据
	              
	                System.out.print(" 用户名: " + name);
	                System.out.print(", 密码: " + password);
	                System.out.print("\n");
	            }
	            // 完成后关闭
	            rs.close();
	            stmt.close();
	            conn.close();
	        }catch(SQLException se){
	            // 处理 JDBC 错误
	            se.printStackTrace();
	        }catch(Exception e){
	            // 处理 Class.forName 错误
	            e.printStackTrace();
	        }
	        finally{
	            // 关闭资源
	            try{
	                if(stmt!=null) stmt.close();
	            }
	            catch(SQLException se2){
	            }// 什么都不做
	            try{
	                if(conn!=null) conn.close();
	            }
	            catch(SQLException se){
	                se.printStackTrace();
	            }
	        }
	    }

	}

The query results are as follows, the query is successful

5. Database insert operation

Note: The addition, deletion and modification of the database only needs to change the SQL statement, and the rest of the code is the same

 Increase:

  String sql="INSERT INTO information(name,password)"+"VALUES('李兴华','011')";

Revise:

 String sql="UPDATE information SET password='111' WHERE name='李华'";

delete:

 String sql="DELETE FROM information WHERE name='李华'";

The complete code for the insert operation is as follows:

package test;
import java.sql.*;
public class Main {
	//定义MySQL的数据库驱动程序
	public static final String DBC="com.mysql.cj.jdbc.Driver";
	//定义MySQL数据库的连接地址,user为数据库名
	 static final String DB_URL = "jdbc:mysql://localhost:3306/user";
	 //数据库的用户名
	  static final String USER = "root";
	 //数据库的密码
	  static final String PASS = "123456";
	public static void main(String[] args)throws Exception {
		// TODO Auto-generated method stub
	      Connection conn = null;//数据库连接
	        Statement stmt = null;//数据库操作
	      String sql="INSERT INTO information(name,password)"+"VALUES('李兴华','011')";
	      Class.forName(DBC);
	      conn=DriverManager.getConnection(DB_URL,USER,PASS);
	      //实例化statement对象
	      stmt=conn.createStatement();
	      //执行数据库更新操作
	      stmt.executeUpdate(sql);
	      //操作关闭
	      stmt.close();
	      //数据库关闭
	      conn.close();
	    }

	}

After running the code, open Navicat, and after refreshing, you can see that the data has been stored in it

6. Database modification operation

Note: The string type should be quoted with ' ', otherwise an error will be reported. For example, Li Hua in the code is a string, which needs to be quoted with single quotes

package test;
import java.sql.*;
public class Main {
	//定义MySQL的数据库驱动程序
	public static final String DBC="com.mysql.cj.jdbc.Driver";
	//定义MySQL数据库的连接地址,user为数据库名
	 static final String DB_URL = "jdbc:mysql://localhost:3306/user";
	 //数据库的用户名
	  static final String USER = "root";
	 //数据库的密码
	  static final String PASS = "123456";
	public static void main(String[] args)throws Exception {
		// TODO Auto-generated method stub
	      Connection conn = null;//数据库连接
	        Statement stmt = null;//数据库操作
	      String sql="UPDATE information SET password='111' WHERE name='李华'";
	      Class.forName(DBC);
	      conn=DriverManager.getConnection(DB_URL,USER,PASS);
	      //实例化statement对象
	      stmt=conn.createStatement();
	      //执行数据库更新操作
	      stmt.executeUpdate(sql);
	      //操作关闭
	      stmt.close();
	      //数据库关闭
	      conn.close();
	    }

	}

After running the code, open Navicat to refresh and check, and found that the password of the user named Li Hua has been changed to 111, and the operation was successful!

 7. Database delete operation

package test;
import java.sql.*;
public class Main {
	//定义MySQL的数据库驱动程序
	public static final String DBC="com.mysql.cj.jdbc.Driver";
	//定义MySQL数据库的连接地址,user为数据库名
	 static final String DB_URL = "jdbc:mysql://localhost:3306/user";
	 //数据库的用户名
	  static final String USER = "root";
	 //数据库的密码
	  static final String PASS = "123456";
	public static void main(String[] args)throws Exception {
		// TODO Auto-generated method stub
	      Connection conn = null;//数据库连接
	        Statement stmt = null;//数据库操作
	      String sql="DELETE FROM information WHERE name='李华'";
	      Class.forName(DBC);
	      conn=DriverManager.getConnection(DB_URL,USER,PASS);
	      //实例化statement对象
	      stmt=conn.createStatement();
	      //执行数据库更新操作
	      stmt.executeUpdate(sql);
	      //操作关闭
	      stmt.close();
	      //数据库关闭
	      conn.close();
	    }

	}

After running, open Navicat and refresh to check, the information named Li Hua has been deleted, and the operation is successful!

Guess you like

Origin blog.csdn.net/lxy20011125/article/details/130211239