【java】对数据库操作的那些事(包含数据库中的预处理)
一、连接问题
前面刚介绍了怎么连接数据库,也写了对应的模板。可是它的可维护性很差。那么怎么解决问题呢?
首先写一个配置文件jdbc.properties
<span style="font-size:18px;">## MySQL
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/hncu? useUnicode=true&characterEncoding=UTF-8
username=root
password=1234 ## Oracle
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@192.168.31.12:1521:orcl
#username=scott
#password=tiger
</span>
然后创建一个生成连接的工厂ConnFactory .java
<span style="font-size:18px;">package cn.hncu.hibernate0; import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties; public class ConnFactory {
private static Connection conn;
static {
try {
//读取配置文件
Properties p = new Properties();
p.load(ConnFactory.class.getClassLoader().getResourceAsStream("jdbc.properties"));
String driver = p.getProperty("driver");
String url = p.getProperty("url");
String username = p.getProperty("username");
String pwd = p.getProperty("password"); Class.forName(driver);
conn = DriverManager.getConnection(url,username,pwd);
System.out.println("已连接到数据库..."+conn);
} catch (Exception e) {
throw new RuntimeException("读取配置文件失败", e);
}
}
public static Connection getConn(){
return conn;
}
public static void main(String[] args) {
getConn();
}
}
</span>
最后直接通过ConnFactory.getConn()获得。
这要做的优点,当改变所要连接的数据库类型时,仅仅须要改动配置文件里的内容就可以。
二、解说getXXX()方法
<span style="font-size:18px;"><span style="white-space:pre"> </span>@Test
public void getXXXDemo() throws Exception{
Statement st = ConnFactory.getConn().createStatement();
String sql = "select * from book";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
Integer id = rs.getInt(1);//这里的1表示数据表中的第一列,以下同理
String name = rs.getString(2);
//Double price = (Double)rs.getObject(3);//出异常,由于内部是採用BigDecimal来处理
Double price = rs.getDouble(3);
Object dateTime = rs.getObject(4);//把日期和时间作为一个总体读取出来
System.out.println(id+","+name+","+price+","+dateTime); String strDateTime = dateTime.toString();
System.out.println(strDateTime);
strDateTime = rs.getDate(4)+"--"+rs.getTime(4);//日期和时间能够单独获取
System.out.println(":::"+strDateTime);
}
ConnFactory.getConn().close();
}</span>
注:对于自己主动增长列。删除之后再插入新记录,序号不会回头,继续往前增长。即中间会出现空号
三、解说Statement中的三个executeXXX()方法
1、executeQuery: 仅仅能运行select语句
2、executeUpdate: 能够运行insert、delete和update语句,但不能运行select
3、execute:增删改查的4种(随意)语句都能运行。该方法若运行非select语句时返回false,运行select语句时返回true,且st对象会缓存该次查询的结果。我
们可通过ResultSet rs = st.getResultSet()来获得结果集
<span style="font-size:18px;"><span style="white-space:pre"> </span>@Test
public void executeXXXDemo() throws Exception{
Statement st = ConnFactory.getConn().createStatement();
String sql = "select * from book";
//String sql = "insert into book(name,price,pub) values('软件project',22.35,'2015-12-05 22:12:23')";
//String sql = "update book set price=38.88 where name='软件project'";
//String sql = "delete from book where name='软件project'";
//st.executeQuery(sql);
//st.executeUpdate(sql);
boolean boo = st.execute(sql); if(boo){
ResultSet rs = st.getResultSet();
while(rs.next()){
System.out.println(rs.getObject(2));
}
}
}</span>
四、数据库查询时防黑技术(预处理语句)
案例、用户登录(通过用户输入信息来拼接sql语句----非常危急)
<span style="font-size:18px;"><span style="white-space:pre"> </span>@Test//用户登录
public void login() throws Exception{
Connection con = ConnFactory.getConn();
Statement st = con.createStatement();
Scanner sc = new Scanner(System.in);
int id = sc.nextInt(); sc.nextLine();
String name = sc.nextLine();
String sql = "select count(*) from stud where id="+id+" and sname='"+name+"'";
System.out.println("sql:"+sql);
ResultSet rs = st.executeQuery(sql);
rs.next();
int a = rs.getInt(1);
if(a<=0){
System.out.println("登录不成功");
}else{
System.out.println("登录成功");
} con.close();
}</span>
黑的方法。输入:1002(回车) 1' or '1'='1
因此:假设须要用 用户输入的信息 来拼接 sql语句,就不能用statement。否则用户能够通过构建where子句中的一个true条件来突破防护对于上面的情
况,应该用PreparedStatement来解决!
<span style="font-size:18px;"><span style="white-space:pre"> </span>@Test//用户登录 黑:1002(回车) 1' or '1'='1
public void login2() throws Exception{
Scanner sc = new Scanner(System.in); Connection con = ConnFactory.getConn();
String sql = "select count(*) from stud where id=? and sname=?";//须要用户输入的地方,用占位符('?')来取代。然后在兴许通过设參来给占位符赋值
PreparedStatement pst = con.prepareStatement(sql);
//设置參数
int id = sc.nextInt(); sc.nextLine();
pst.setInt(1, id); //參数1----代表第1个占位符
String name = sc.nextLine();
pst.setString(2, name);//參数2 ResultSet rs = pst.executeQuery(); rs.next();
int a = rs.getInt(1);
if(a<=0){
System.out.println("登录不成功");
}else{
System.out.println("登录成功");
} con.close();
}</span>
五、获取自己主动增长列(如id)
<span style="font-size:18px;"><span style="white-space:pre"> </span>@Test //演示获取自己主动增长列如id
public void saveAuto() throws Exception{
Connection con = ConnFactory.getConn();
String sql = "insert into book(name,price,pub) values('JavaEE',100.8,'2013-06-12 08:30:30')";
Statement st = con.createStatement(); //st.executeUpdate(sql);
st.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
ResultSet rs = st.getGeneratedKeys();//里面封装了自己主动生成的全部值
if(rs.next()){
int id = rs.getInt(1);//获取第1个自己主动增长列
System.out.println("自己主动增长的id:"+id);
}
System.out.println("-----------------"); //预处理语句
sql = "insert into book(name,price) values(?,?)";
PreparedStatement pst = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
pst.setString(1, "计算机基础");
pst.setDouble(2, 28);
pst.executeUpdate();
ResultSet rs2 = pst.getGeneratedKeys();//里面封装了自己主动生成的全部值
if(rs2.next()){
int id = rs2.getInt(1);//获取第1个自己主动增长列
System.out.println("自己主动增长的id:"+id);
}
}</span>
六、演示批处理语句
public void batch() throws Exception{
Connection con = ConnFactory.getConn();
String sql = "insert into book(name,price,pub) values('JavaEE',100.8,'2015-06-12 08:30:30')";
Statement st = con.createStatement();
for(int i=0;i<10;i++){
st.addBatch(sql);
}
sql = "update book set price=price*1.1 where price>100";
st.addBatch(sql);
int[] a = st.executeBatch();
for(int r:a){
System.out.println(r);//r为每条sql语句所影响的记录数
}
}
预处理
public void preparedBatch() throws Exception{
Connection con = ConnFactory.getConn();
String sql = "insert into book(name,price,pub) values(?,?,?)";
PreparedStatement pst = con.prepareStatement(sql);
for(int i=0;i<5;i++){
pst.setString(1, "Java"+i);
pst.setDouble(2, 55.85+i);
pst.setString(3, "2016-12-10 07:07:08");
pst.addBatch(); //pst的方式不能带參数sql
}
//pst.executeBatch();
int[] a = pst.executeBatch();
for(int r:a){
System.out.println(r);//r为每条sql语句所影响的记录数
}
}
注意:预处理的方式不能带參数sql,普通的须要
【java】对数据库操作的那些事(包含数据库中的预处理)的更多相关文章
- python sqlite3操作类扩展,包含数据库分页
一.原因 最近在使用python3和sqlite3编辑一些小程序,由于要使用数据库,就离不开增.删.改.查,sqlite3的操作同java里的jdbc很像,于是就想找现成的操作类,找来找去,发现一个 ...
- 实验3、Flask数据库操作-如何使用Flask与数据库
1. 实验内容 数据库的使用对于可交互的Web应用程序是极其重要的,本节我们主要学习如何与各种主要数据库进行连接和使用,以及ORM的使用 2. 实验要点 掌握Flask对于各种主要数据库的连接方法 掌 ...
- java 对excel操作导入excel数据到数据库
加入jar包jxl.jar ===================services层掉用工具类==================================== // 导入 public Lis ...
- 一些常用数据库操作在mysql及sql server中实现方式的差异
因为本文强调的是不同点,所以先讲述不同点,再讲相同点. 一.不同点 1.创建表时主键id的自增实现方式不一样 mysql数据库的实现方式是auto_increment,示例如下 CREATE TABL ...
- 使用JdbcTemplate简化JDBC操作 实现数据库操作
使用Spring JDBC框架方遍简单的完成JDBC操作,满足性能的需求且灵活性高. Spring JDBC框架由4个部分组成,即core.datasource.object.support. org ...
- Django模型-数据库操作
前言 前边记录的URLconf和Django模板全都是介绍页面展示的东西,也就是表现层的内容.由于Python先天具备简单而强大的数据库查询执行方法,Django 非常适合开发数据库驱动网站. 这篇开 ...
- iOS学习笔记(十五)——数据库操作(SQLite)
SQLite (http://www.sqlite.org/docs.html) 是一个轻量级的关系数据库.SQLite最初的设计目标是用于嵌入式系统,它占用资源非常少,在嵌入式设备中,只需要几百K的 ...
- IOS数据库操作SQLite3使用详解(转)
iPhone中支持通过sqlite3来访问iPhone本地的数据库.具体使用方法如下1:添加开发包libsqlite3.0.dylib首先是设置项目文件,在项目中添加iPhone版的sqlite3的数 ...
- PhoneGap 数据库操作
1,openDatabase phonegap官方文档中已经很清楚的标明,如果使用一个数据库首先要用window对象进行创建: var dbShell = window.openDatabase(na ...
随机推荐
- 封装boto3 api用于服务器端与AWS S3交互
由于使用AWS的时候,需要S3来存储重要的数据. 使用Python的boto3时候,很多重要的参数设置有点繁琐. 重新写了一个类来封装操作S3的api.分享一下: https://github.com ...
- Python开发基础-Day5-字符编码、文件处理和函数基础(草稿)
字符编码 为什么要有字符编码? 字符编码是为了让计算机能识别我们人写的字符,因为计算机只认识高低电平,也就是二进制数"0","1". 一个文件用什么编码方式存储 ...
- 【BFS】Pots
[poj3414]Pots Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 16925 Accepted: 7168 ...
- 【构造】Codeforces Round #405 (rated, Div. 1, based on VK Cup 2017 Round 1) A. Bear and Different Names
如果某个位置i是Y,直接直到i+m-1为止填上新的数字. 如果是N,直接把a[i+m-1]填和a[i]相同即可,这样不影响其他段的答案. 当然如果前面没有过Y的话,都填上0就行了. #include& ...
- 20172333 2017-2018-2 《Java程序设计》第5周学习总结
20172333 2017-2018-2 <Java程序设计>第5周学习总结 教材学习内容 1.if语句.if-else语句.switch语句 都是通过对于布尔表达式的结果来进行是否执行下 ...
- NHibernate之一级缓存(第十篇)
NHibernate的一级缓存,名词好像很牛B,很难.实际上就是ISession缓存.存储在ISession的运行周期内.而二级缓存则存储在ISessionFactory内. 一.ISession一级 ...
- 移动端touchstart事件穿透问题,解决方案
[来源]:在开发移动端网站时,会经常徘徊在click和touchstart之间:因为touchstart虽然好用和快速响应:但是其缺点也是显而易见的,当我们大面积的使用touchstart的时候就会遇 ...
- 【转】Python IDE for Eclipse
原文地址 PyDev is a plugin that enables Eclipse to be used as a Python IDE (supporting also Jython and I ...
- ADO特有的流化和还原
ADO特有的流化和还原 {*******************************************************}{ }{ ADO 数据流化 }{ }{ 版权所有 (C) 20 ...
- [Eclipse插件] 安装和使用JD-Eclipse插件
JD-Core 是一个免费的库,从一个或多个“.class”文件中 重构Java源代码.JD-Core可以用来恢复丢失的源代码,并深究Java运行时类库.支持Java 5的功能:如注释,泛型或键入“枚 ...