Operate MySQL database in java JDBC mode

Preliminary preparation:

1 First you need to install mysql database software

2 Download the mysql JDBC driver from the mysql official website. The driver must be consistent with the mysql version, but I did not find a driver consistent with my mysql version. I only saw the 5.1.44 version, let's try it. After downloading, unzip to get the mysql-connector-java-5.1.44-bin.jar file

3 Set the driver classpath

Method 1: Add the driver path information in the environment variable classpath.

Method 2: Copy the driver to the application class path (src directory of the project). Then in eclipse, right-click the project name, in the drop-down menu, select build path -> configure build path to open the dialog box and select the Libraries tab, click Add JARs, select the jar package just placed in the src directory and click OK to complete the configuration.

If it is a WEB project, just copy the driver to the webRoot\WEB-INF\lib directory, and eclipse will automatically add the class library in the lib directory to the class path.

Create a test database and add data:

CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(20) NOT NULL,
 `phone` varchar(15) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `name` (`name`),
 KEY `phone` (`phone`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


INSERT INTO `user` (`id`, `name`, `phone`) VALUES
(1, 'king', '13100000000'),
(2, 'queen', '13111111111');


Basic use

package JdbcMysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MysqlOperator {
	// java jdbc操作mysql数据库基本步骤
	// 1  加载JDBC驱动
	// 2 创建数据库连接
	// 3 创建Statement对象
	// 4 执行sql语句,返回结果集对象ResultSet
	// 5 处理返回的结果
	// 6 关闭创建的各对象
    final static String driver = "com.mysql.jdbc.Driver";
    final static String url = "jdbc:mysql://localhost:3306/test";
    final static String user = "root";
    final static String password = "root";
    
    // 加载驱动程序
    static {
    	try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
    }
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
	  
		// 创建连接
		Connection conn = getConn();
         if(conn==null){
        	 System.out.println("创建连接失败");
        	 System.exit(0);
         }
         // 创建Statement对象
         Statement stmt = conn.createStatement();
         String sql = "select * from user";
         // 执行sql查询
         ResultSet res = stmt.executeQuery(sql);
         // 从结果集中取数据   可以按列名称取值    也可以按索引号取值
         while(res.next()){
        	 System.out.println(res.getString("name")+"---"+res.getString("phone"));
         }
         
         // PreparedStatement 的基本用法  带条件查询
         ResultSet res1 = getResultSetByPhone("13100000000",conn);
         while(res1.next()){
        	 System.out.println(res1.getString("name")+"---"+res1.getString("phone"));
         }
         
         // 关闭连接
         closeConn(conn);
         
	}
	
	// 创建连接
	public static Connection getConn() throws SQLException{
		Connection conn = null;
		conn = DriverManager.getConnection(url,user,password);
		return conn;
	}
 
	// 关闭连接
	public static void closeConn(Connection conn) throws SQLException{
		if(conn!=null&&!conn.isClosed()){
			conn.close();
		}
	}
	
	// 封装一个带条件查询
	public static ResultSet getResultSetByPhone(String phone,Connection conn) throws SQLException{
		String sql = "select * from user where phone=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, phone);
		return pstmt.executeQuery();
	}

}

With the above foundation, we need to conduct an in-depth study of the Connection Statement ResultSet objects involved in order to achieve more advanced operations on mysql, such as insert, modify, delete, call stored procedures, and implement transactions.



Guess you like

Origin blog.csdn.net/wang740209668/article/details/78450898