您的位置:首页 > 编程语言 > Java开发

JDBC用法JAVA266-276

2016-07-10 00:10 567 查看
来源:http://www.bjsxt.com/

一、S03E266_01JDBC_设计架构、驱动类加载、建立Connection、效率测试













package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
* 测试跟数据库建立连接
*/
public class Demo01 {
public static void main(String[] args) {
try {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
long start = System.currentTimeMillis();
//建立连接(连接对象内部其实包含了Socket对象,是一个远程的连接。比较耗时!这是Connection对象管理的一个要点!)
//真正开发中,为了提高效率,都会使用连接池来管理连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
long end = System.currentTimeMillis();
System.out.println(conn);
System.out.println("建立连接,耗时:"+(end-start)+"ms");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


控制台输出:
com.mysql.jdbc.JDBC4Connection@181eda8
建立连接,耗时:500ms


二、S03E267_01JDBC_statement接口用法、SQL注入



package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
* 测试Statement接口的用法,执行SQL语句,以及SQL注入问题
*/
public class Demo02 {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

Statement stmt = conn.createStatement();
/*          String name = "赵六";
String sql = "insert into t_user(userName,pwd,regTime)values('"+name+"','666666',now())";
stmt.execute(sql);*/

//测试SQL注入(恶意攻击)
String id = 5 + " or 1=1";//1=1永远true,数据全被删除
String sql = "delete from t_user where id = " + id;
stmt.execute(sql);

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


三、S03E268_01JDBC_PreparedStatement用法、占位符、参数处理

package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
* 测试PreparedStatement的基本用法
*/
public class Demo03 {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

String sql = "insert into t_user (userName,pwd,regTime) value (?,?,?)"; //?占位符
PreparedStatement ps = conn.prepareStatement(sql);

//          ps.setString(1, "小高");  //参数索引是从1开始计算,而不是0,其它的外包可能是0,注意一下
//          ps.setString(2, "123");
//          ps.setDate(3, new java.sql.Date(System.currentTimeMillis()));   //java.util.Date的子类

//可以使用setObject方法处理参数,不用考虑类型,方便点
ps.setObject(1, "小高2");
ps.setObject(2, "234");
ps.setObject(3, new java.sql.Date(System.currentTimeMillis()));

System.out.println("插入一行记录");
//          ps.execute();   //返回ResultSet则为true,返回更新行数或没有结果则为false
int count = ps.executeUpdate(); //返回更新行数
System.out.println(count);

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


四、S03E269_01JDBC_ResultSet结果集用法、游标原理、关闭连接问题



package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* 测试ResultSet结果集的基本用法
*/
public class Demo04 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

String sql = "select id,userName,pwd from t_user where id>?";   //?占位符
ps = conn.prepareStatement(sql);

ps.setObject(1, 2); //把id大于2的记录都取出来

rs = ps.executeQuery();

while (rs.next()) {
System.out.println(rs.getInt(1)+"--"+rs.getString(2)+"--"+rs.getString(3));
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{

//遵循:ResultSet-->Statement-->Connection这样的关闭顺序!一定要将三个trycatch块,分开写!
try {
if (rs!=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps!=null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


五、S03E270_01JDBC_批处理Batch、插入2万条数据的测试



package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
* 测试ResultSet结果集的基本用法
*/
public class Demo05 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

conn.setAutoCommit(false); //设为手动提交

long start = System.currentTimeMillis();

stmt = conn.createStatement();
for (int i = 0; i < 20000; i++) {
stmt.addBatch("insert into t_user (userName,pwd,regTime) values ('hao" + i + "',666666,now())");
}
stmt.executeBatch();
conn.commit();  //提交事务

long end = System.currentTimeMillis();
System.out.println("插入200000条数据,耗时(ms):" + (end - start));

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{

try {
if (stmt!=null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


六、S03E271_01JDBC_事务概念、ACID特点、隔离级别、提交commit、回滚rollback







package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
* 测试事务的基本概念和用法
*/
public class Demo06 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

conn.setAutoCommit(false); //JDBC中默认是true,自动提交事务

ps1 = conn.prepareStatement("insert into t_user(userName,pwd)values(?,?)"); //事务开始
ps1.setObject(1, "小高");
ps1.setObject(2, "123");
ps1.execute();
System.out.println("第一次插入");

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

ps2 = conn.prepareStatement("insert into t_user(userName,pwd)values(?,?,?)");   //模拟执行失败(values的参数写成三个了)
//insert时出现异常,执行conn.rollback
ps2.setObject(1, "小张");
ps2.setObject(2, "678");
ps2.execute();
System.out.println("第二次插入");

conn.commit();

} catch (ClassNotFoundException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
} finally{

try {
if (ps1!=null) {
ps1.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps2!=null) {
ps2.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


控制台输出:
第一次插入
java.sql.SQLException: No value specified for parameter 3
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2611)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2586)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2510)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1316)
at com.test.jdbc.Demo06.main(Demo06.java:39)


七、S03E272_01JDBC_时间处理、Date_Time、Timestamp区别、随机日期生成



package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Random;

/**
* 测试时间处理(java.sql.Date,Time,Timestamp)
*/
public class Demo07 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

for (int i = 0; i < 1000; i++) {

ps = conn.prepareStatement("insert into t_user(userName,pwd,regTime,lastLoginTime)values(?,?,?,?)");
ps.setObject(1, "小高" + i);
ps.setObject(2, "123");

//
int random = 1000000000 + new Random().nextInt(1000000000); //随机时间

java.sql.Date date = new java.sql.Date(System.currentTimeMillis() - random);    //插入随机时间
java.sql.Timestamp stamp = new Timestamp(System.currentTimeMillis());   //如果需要插入指定时间,可以使用Calendar、DateFormat
ps.setDate(3, date);
ps.setTimestamp(4, stamp);
//
ps.execute();
}

System.out.println("插入");

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{

try {
if (ps!=null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


八、S03E273_01JDBC_时间操作、时间段和日期段查询

package com.test.jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
* 测试时间处理(java.sql.Date,Time,Timestamp),取出指定时间段的数据
*/
public class Demo08 {

/**
* 将字符串代表的时间转为long数字(格式:yyyy-MM-dd hh:mm:ss)
* @param dateStr
* @return
*/
public static long str2DateTime(String dateStr){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

try {
return format.parse(dateStr).getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}

public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

//
ps = conn.prepareStatement("select * from t_user where regTime > ? and regTime < ?");
java.sql.Date start = new java.sql.Date(str2DateTime("2016-06-20 00:00:00"));
java.sql.Date end = new java.sql.Date(str2DateTime("2016-06-24 00:00:00"));

ps.setObject(1, start);
ps.setObject(2, end);

rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getInt("id") + "--" + rs.getString("userName")+"--"+rs.getDate("regTime"));
}
//

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{

try {
if (ps!=null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


九、S03E274_01JDBC、CLOB文本大对象操作



package com.test.jdbc;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* 测试CLOB   文本大对象的使用
* 包含:将字符串、文件内容插入数据库中的CLOB字段和将CLOB字段值取出来的操作。
*/
public class Demo09 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement ps2 = null;
ResultSet rs = null;
Reader r = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

//插入//
ps = conn.prepareStatement("insert into t_user(userName,myInfo)values(?,?)");
ps.setString(1, "小高");

//将文本文件内容直接输入到数据库中
//          ps.setClob(2, new FileReader(new File("G:/JAVA/test/a.txt")));

//将程序中的字符串输入到数据库中的CLOB字段中
ps.setClob(2, new BufferedReader(new InputStreamReader(new ByteArrayInputStream("aaaa".getBytes()))));

ps.executeUpdate();
System.out.println("插入");
//

//查询//
ps2 = conn.prepareStatement("select * from t_user where id=?");
ps2.setObject(1, 223021);

rs = ps2.executeQuery();
System.out.println("查询");
while (rs.next()) {
Clob c = rs.getClob("myInfo");
r = c.getCharacterStream();
int temp = 0;
while ((temp=r.read())!=-1) {
System.out.print((char)temp);
}
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally{

try {
if (r!=null) {
r.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (rs!=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps2!=null) {
ps2.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps!=null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


十、S03E275_01JDBC_BLOB、二进制大对象的使用



package com.test.jdbc;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* 测试BLOB   二进制大对象的使用
*/
public class Demo10 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement ps2 = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");

//插入//
ps = conn.prepareStatement("insert into t_user(userName,headImg)values(?,?)");
ps.setString(1, "小高");
ps.setBlob(2, new FileInputStream("G:/JAVA/test/d.jpg"));
ps.execute();
//

//查询//
ps2 = conn.prepareStatement("select * from t_user where id=?");
ps2.setObject(1, 223024);

rs = ps2.executeQuery();
System.out.println("查询");
while (rs.next()) {
Blob b = rs.getBlob("headImg");
is = b.getBinaryStream();
os = new FileOutputStream("G:/JAVA/test/h.jpg");

int temp = 0;
while ((temp=is.read())!=-1) {
os.write(temp);
}
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally{

try {
if (os!=null) {
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (is!=null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (rs!=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps2!=null) {
ps2.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps!=null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


十一、S03E276_01JDBC_代码总结、简单封装、资源文件properties处理连接信息

#右击该properties文件--properties--Resource--Text file encoding,选中other,选择其它编码方式。
#如UTF-8或GBK,这样就能在properties里面输入中文,而不会自动转成Unicode了。

#java中的properties文件是一种配置文件,主要用于表达配置信息。
#文件类型为*.properties,格式为文本文件,文件内容是"键=值"的格式。
#在properties文件中,可以用"#"来作注释

#MySQL连接配置
mysqlDriver=com.mysql.jdbc.Driver
mysqlURL=jdbc:mysql://localhost:3306/testjdbc
mysqlUser=root
mysqlPwd=mysql

#Oracle连接配置
#...


package com.test.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {

static Properties pros = null;  //可以帮助读取和处理资源文件中的信息

static {    //加载JDBCUtil类的时候调用
pros = new Properties();
try {
pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}

public static Connection getMysqlConn(){
try {
Class.forName(pros.getProperty("mysqlDriver"));
return DriverManager.getConnection(pros.getProperty("mysqlURL"),
pros.getProperty("mysqlUser"),pros.getProperty("mysqlPwd"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//可以重载多个,这里就懒得写了
public static void close(ResultSet rs,Statement st,Connection conn){

try {
if (rs!=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (st!=null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}


package com.test.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
* 测试使用JDBCUtil工具类来简化JDBC开发
*/
public class Demo11 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
conn = JDBCUtil.getMysqlConn();

ps = conn.prepareStatement("insert into t_user (userName) values (?)");
ps.setString(1, "小高高");
ps.execute();

} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCUtil.close(rs, ps, conn);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JDBC 数据库 java