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();