java基础之JDBC连接数据库

本文详细介绍了使用Java标准JDBC进行数据库操作的步骤,包括加载驱动、创建连接、执行SQL语句等,并提供了示例代码,同时介绍了如何使用PreparedStatement防止SQL注入攻击。

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

JDBC连接数据库

使用框架多了,对JDBC连接数据库有点陌生,记录一下:
使用java基础的JDBC,要记住步骤
加载驱动、创建连接、创建语句、执行语句、处理结果、关闭资源
准备工作:

	String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/samp_db";
    String username = "root";
    String password = "";
    Connection conn = null;

1.加载驱动:

Class.forName(driver);

2.创建连接:

conn = (Connection) DriverManager.getConnection(url, username, password);

3.创建语句:

选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!
排序:select * from table1 order by field1,field2 [desc]
总数:select count as totalcount from table1
求和:select sum(field1) as sumvalue from table1
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1

4.执行语句:

Statement statement=conn.createStatement();
PreparedStatement pstatement=conn.prepareStatement(所要执行的sql语句);
pstatement.setString(第一个占位符, 占位符的内容);
pstatement.setString(第二个占位符, 占位符的内容);
利用PreparedStatement可以避免数据库的注入攻击!

pstmt = (PreparedStatement) conn.prepareStatement(sql);

5.处理结果:

ResultSet rs=statement.executeQuery(Sql);或者ResultSet rs=pstatement.executeQuery();
执行查询语句是用executeQuery();
但是在执行“插入”,“更新”“删除”语句时就需要用executeUpdate();方法了

一般用while循环
while(rs.next()){
依次读取结果。
}

6.关闭资源:

依次将ResultSet对象,Statement对象或PerparedStatement对象Connection对象关闭释放所占用的资源
rs.close();
statement.close();或者pstatement.close();
conn.close();

OK,这就搞定了。不过现在都用数据库连接池,提高效率。

补充:

ThreadLocal: 线程本地变量,为变量在每一个线程中创建一个副本。不需要共享。
原因:1>线程安全;2>不用多线程,提高效率。
例子:

ThreadLocal获取数据库连接

 private static final ThreadLocal<Connection> CONNECTION_HOLDER;
 CONNECTION_HOLDER = new InheritableThreadLocal<>();
 Connection conn = CONNECTION_HOLDER.get();
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值