再次学习jdbc有感
二次学习jdbc有感
信息配置(必需)
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
String username="root";
String password="123456";
配置驱动(必需)
Class.forName("com.mysql.cj.jdbc.Driver");
在maven中配置(必需)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
事务详解(提交和回滚)
package com.wang;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class jdbc01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
String username="root";
String password="123456";
//配置驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
Connection connection= null;
try {
connection = DriverManager.getConnection(url,username,password);
connection.setAutoCommit(false);
String select="select * from user";
PreparedStatement preparedStatement=connection.prepareStatement(select);
ResultSet resultSet=preparedStatement.executeQuery();
while(resultSet.next())
{
int id= resultSet.getInt(1);
String NAME=resultSet.getString(2);
int PASSWORD=resultSet.getInt(3);
String email=resultSet.getString(4);
System.out.println(id);
System.out.println(NAME);
}
connection.commit();
System.out.println("success");
} catch (SQLException e) {
connection.rollback();
throw new RuntimeException(e);
}
finally {
connection.close();
}
}
}
释放资源三件
resultSet.close();
preparedStatement.close();
connection.close();
连接数据库(地址,用户,密码)
connection= DriverManager.getConnection(url,username,password);
sql获取
//向数据库发送SQL的对象Statement:增删改查
Statement statement = connection.createStatement();
Statement详解
执行sql语句
两种执行方式:
1.ResultSet resultSet = statement.executeQuery(sql);
ResultSet集合,最终获取到的是一个集合,这个集合里面存的是执行sql语句后的结果,对应的方法是executeQuery,这个方法是经行“查询”的语句
2.int i = statement.executeUpdate(sql);
executeUpdate这个方法是经行更改的语句,例如更删改等,最后返回的是一个数,这个数取决于执行了多少条语句。
preparedStatement预编译详解
这个语句可以防止sql注入,运用范围广
String sql="select * from jdbc.user where id=? and password=?";
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
preparedStatement.setInt(2,123456);
ResultSet resultSet =preparedStatement.executeQuery();
看以上代码,预编译sql语句,该sql语句将id和password位置,在后面用preoaredStatement里的方法按照数据类型以及编号依次输入,最后用executeQuery()方法执行
防止sql注入的原理就是转义字符来转义
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术