JDBC操作MySQL数据库

本文详细介绍JDBC在Java中连接数据库的五大步骤:加载数据库驱动、创建数据库连接、使用Statement和PreparedStatement进行查询、获取结果及关闭资源。重点推荐使用PreparedStatement预编译SQL,提升效率与安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JDBC(Java Data Base Connectivity)

JDBC是用于Java连接数据库。
创建JDBC查询有五大步骤

1. 加载数据库驱动

Java默认不包含数据库驱动,需要自己下载并导入。

  • 会抛出ClassNotFoundException异常
try {
    Class.forName(CLASSNAME); //加载驱动
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

CLASSNAME是字符串形式的对应数据库的包名
如,MySQL的 CLASSNAME = "com.mysql.jdbc.Driver”

2. 创建数据库连接

加载好驱动后,就可以连接数据库了

  • 会抛出SQLException异常
try {
    connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); //创建数据库连接
} catch (SQLException e) {
    e.printStackTrace();
}
//下面以MySQL举例
//DB_URL,USERNAME,PASSWORD均为字符串形式
//DB_URL = "jdbc:mysql://ip:port/数据库名"
//USERNAME=用户名
//PASSWORD=用户密码

3. 进行查询

查询时会用到Statement(静态)PreparedStatement(动态)对象
建议使用PreparedStatement(动态)

  • 会抛出SQLExcpetion异常

Statement

Statement statement = null; //查询对象
ResultSet resultSet = null; //查询结果
try {
    //创建查询对象
    statement = connection.createStatement();
    String sql = "SQL语句";
    //执行查询,结果保存在ResultSet中
    resultSet = statement.executeQuery(sql);
    //增删改时,使用executeUpdate,返回受影响的行数
    // int result = statement.executeUpdate(sql);
}catch (SQLException e) {
	e.printStackTrace();
}

PreparedStatement(推荐使用)

Statement使用字符串拼接获得SQL语句,可能会出错,而且影响性能,所以常用预编译SQL对象——PreparedStatement

PreparedStatement preparedStatement = null; // 查询对象
ResultSet resultSet = null; // 查询结果
try{
	//SQL语句使用'?'表示变量
	//如:String sql = "select * from user where username= ? and host= ?;"
	preparedStatement = connection.prepareStatement("SQL语句");
	//填充SQL中的变量,把x填入第i个'?'
	preparedStatement.setType(i,x);
	//如:String name = 'admin'; String  host = "localhost";
	//preparedStatement.setString(1, name);//第一个?为String型,填充name
	
	//因为SQL语句之前已经设置,这里的executeQuery无参
	resultSet = preparedStatement.executeQuery();//执行查询
	//增删改时,使用executeUpdate,无参,返回受影响的行数
	//int result = preparedStatement.executeUpdate();
}catch (SQLException e){
	e.printStackTrace();
}

Statement和PreparedStatement的区别

共同点:

  1. forName(CLASSNAME); //加载驱动
  2. Connection connection = DriverManager.getConnection(DB_URL,USERNAME,PASSWORD); //建立数据库连接

不同点:

Statement
  1. Statement statement = connection.createStatement(); //创建查询对象
    String sql = “具体的SQL语句”; //创建具体的SQL语句
  2. ResultSet resultSet = statement.excuteQuery(sql) //得到查询结果
  3. resultSet.close(); //依次关闭连接
    statement.close();
    connection.close();
PreparedStatement
  1. String sql = “带?的sql” ;//创建带参数的SQL语句
    PreparedStatement preparedStatement = connectioin.PrepareStatement(sql预处理); //预编译SQL语句
    preparedStatement.setType(1,“dfd”);
    preparedStatement.setString(2,“asdfas”);
  2. ResultSet resultSet = preparedStatement.excuteQuery(); //得到查询结果
  3. resultSet.close(); //依次关闭连接,会抛出异常,后面有详细讲解
    preparedStatement.close();
    conneciton.close();

两种查询的区别

类型SQL生成方式SQL语句的填写示例
Statement字符串拼接execute执行时填写SQLexecuteUpdate(“SQL”);
PreparedStatement预编译填充声明时将预编译SQL作为参数conn.preparedStatement(“预编译SQL”);

增删改

增删改后,需执行connection.commit()提交,遇到错误时,可使用connection.rollback()回滚

4. 获取结果

查询的结果会保存在ResultSet对象中,需要读取为Java类型的数据

//获取查询结果
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {//使游标移至第一行
	Type vari = resultSet.getType("列名");
	//例如
    //String col1 = resultSet.getString("col1");
    //Int col2 = resultSet.getInt("col2");
}

ResultSet是一个表,游标位于第一行之前,需要使用next()使游标移至下一行

5. 关闭资源

ResultSetStatement/PreparedStatementConnection在使用完后需要关闭
try...catch后添加finally

try{
	...
}catch(...){
	...
}finally{
	if(resultSet != null){
		try{
			resultSet.close();
		}catch(SQLException e){
		}
	if(statement != null) {// 或 (preparedStatement != null)
		try{
			statement.close(); //或 preparedStatement.close()
		}catch(SQLException e){
		}
	if(connection != null){
		try{
			connection.close();
		}catch(SQLException e){
		}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值