JDBC的使用

JDBC的使用

使用前需在module-info.java中添加 requires java.sql;

一般步骤

  • 注册驱动,JDBC4.0后不需要注册
  • 使用DriverManger连接数据库
  • 通过Connection创建SQL语句
  • 通过Statement获取结果集
  • 处理结果集
  • 释放资源

导入包

Eclipse导入jar包

在导入java.sql时,要先导入mysql-connector-java的jar包,否则无法运行。
方法如下:
右键项目包,点击Properties,进入如下界面:

后选择Java Build Path

点击Add External JARS**,找到文件的jar包所在位置导入。

IDEA导入jar包

快捷键:Ctrl + Alt + Shift + s打开Project Structure

点击Modules,点击Depedencies后,右侧有个+号标志,点击找到jar的位置并且导入。

import java.sql.*;

加载驱动

String driveName="com.mysql.jdbc.Driver";
Class.forName("driveName");

使用DricerManger连接数据库

String URL="jdbc:mysql://localhost:3306/数据库名";
String userName="root";
String password="";
jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Chongqing&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&verifyServerCertificate=false&autoReconnct=true&autoReconnectForPools=true&allowMultiQueries=true
Connection conn = DriverManager.getConnection(URL, userName, password);

通过Connection创建SQL语句

Statement:

Statement stmt = conn.createStatement();
String sql;
sql="SQL语句";
ResultSet rs = stmt.executeQuery(sql);

PreparedStatement:

String sql = "select *from user where username=? and password= ?";//问号表示要执行的目标对象
stmt = conn.prepareStatement(sql);//提前告知执行语句
stmt.set具体类型(第几个问号,替换问号);
stmt.setString(1, usersName);
stmt.setString(2, password);

使用 Statement 对象执行语句: executeQuery、executeUpdate 和execute
execute:用于执行返回多个结果集、多个更新计数或二者组合的语句
executeQuery:用于产生单个结果集的语句
executeUpdate:用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQLDDL(数据定义语言)语句,executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。

工具类的编写

JBDCutils:

import java.sql.*;
public class DButil {
	static String URL="jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Chongqing&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&verifyServerCertificate=false&autoReconnct=true&autoReconnectForPools=true&allowMultiQueries=true";
	static String userName="root";
	static String password= "";
	/*建立连接(测试成功)*/
	public static Connection getConnection(Connection conn) throws SQLException{
		conn=DriverManager.getConnection(URL,userName,password);
		return conn;
	}
	/*关闭连接(测试成功)*/
	public static void closeConnection(Connection conn) {
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/*释放资源(测试成功)*/
	public static void realeaseAll(ResultSet rs, Statement st,Connection conn) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(st!=null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

DButils:

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DbUtils {

    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        try {
            InputStream in = DbUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //驱动只用加载一次
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
    /**
     * 释放连接资源
     *
     * @param conn
     * @param st
     * @param res
     */
    public static void release(ResultSet res, Statement st,Connection conn ) {
        if (res != null) {
            try {
                res.close();
            } catch (SQLException throwable) {
                throwable.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException throwable) {
                throwable.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwable) {
                throwable.printStackTrace();
            }
        }
    }
}

DButils(连接池):

public class DbUtils {

    private static DataSource dataSource;
    //加载配置文件
    static {
        try{
            Properties properties = new Properties();
            InputStream inputProperties = DbUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputProperties);
            dataSource = DruidDataSourceFactory.createDataSource(properties);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }


    /*释放资源*/
    public static void release(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
原文地址:https://www.cnblogs.com/960223447a/p/15773888.html