知识点:
1、JDBC(Java Data Base Connectivity,java数据库连接),由一些接口和类构成的API。J2SE的一部分,由java.sql,javax.sql包组成。
2、连接数据库步骤:(6部曲)
a、注册驱动 (只做一次):
Class.forName(“com.mysql.jdbc.Driver”);
推荐这种方式,不会对具体的驱动类产生依赖。
DriverManager.registerDriver(com.mysql.jdbc.Driver);
会造成DriverManager中产生两个一样的驱动,并会对具体的驱动类产生依赖。
System.setProperty(“jdbc.drivers”, “driver1:driver2”);
虽然不会对具体的驱动类产生依赖;但注册不太方便,所以很少使用。
b、建立连接(Connection) :
Connection conn = DriverManager.getConnection(url, user, password);
url格式:
JDBC:子协议:子名称//主机名:端口/数据库名?属性名=属性值&…
User,password可以用“属性名=属性值”方式告诉数据库;
其他参数如:useUnicode=true&characterEncoding=GBK
c、创建执行SQL的语句(Statement):
d、执行语句:
Statement
Statement st = conn.createStatement();
st.executeQuery(sql);
PreparedStatement
String sql = “select * from table_name where col_name=?”;
PreparedStatement ps = conn.preparedStatement(sql);
ps.setString(1, “col_value”);
ps.executeQuery();
e、处理执行结果(ResultSet):
ResultSet rs = statement.executeQuery(sql);
While(rs.next()){
rs.getString(“col_name”);
rs.getInt(“col_name”);
//…
}
f、释放资源:
释放ResultSet, Statement,Connection.
数据库连接(Connection)是非常稀有的资源,用完后必须马上释放,如果Connection不能及时正确的关闭将导致系统宕机。Connection的使用原则是尽量晚创建,尽量早的释放
1、Test.java(简单连接入门还有不足)
package com.jdbc;
import java.sql.Connection;
import java.sql.DriverAction;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
demo();
}
static void demo() throws SQLException, ClassNotFoundException {
// 1、下面是三种注册驱动的方法,(推荐第二种)
// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
// System.setProperty("jdbc,drivers", "com.mysql.jdbc.driver");
String url = "jdbc:mysql://localhost:3306/ghq";
String user = "root";
String password = "admin";
// 2、建立连接
Connection conn = DriverManager.getConnection(url, user, password);
// 3、创建语句
Statement st = conn.createStatement();
// 4、执行语句
String sql = "select * from mytest";
ResultSet re = st.executeQuery(sql);
// 打印输出语句
while (re.next()) {
System.out.println(re.getInt("id") + re.getString("name") + re.getInt("age") + re.getDate("birthday"));
}
// 关闭资源
re.close();
st.close();
conn.close();
}
}
2、建立jdbc的工具类(JdbcUtil.java)
package com.jdbc.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtil {
private static String url = "jdbc:mysql://localhost:3306/ghq";
private static String user = "root";
private static String password = "admin";
//静态代码块在加载虚拟机时只被虚拟机加载一次
static void demo() {
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError();
}
}
//建立连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
//关闭资源(原则是后放进的先关闭)
public static void closeTest(Connection conn, Statement st, ResultSet re) {
//要用finally保证每个资都关闭
try {
//判断re是否为空
if (re != null)
re.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
2.1、CRUD.java(增删改查)
package com.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.jdbc.util.JdbcUtil;
public class CRUD {
private static String Csql = "insert into mytest(id,name,age,birthday) values ('4','woaini',20,'2008/09/09')";
private static String Dsql = "delete from mytest where id > 3";
private static String Usql = "update mytest set name = 'guanhuaqin' where id = 3";
private static String Rsql = "select id,name,age,birthday from mytest";
private static String url = "jdbc:mysql://localhost:3306/ghq";
private static String user = "root";
private static String password = "admin";
public static void main(String[] args) {
// create();
// delete();
// update();
read();
}
// 增加数据
static void create() {
Connection conn = null;
Statement st = null;
ResultSet re = null;
try {
conn = DriverManager.getConnection(url, user, password);
st = conn.createStatement();
// 返回的是关联到的数据条数
int i = st.executeUpdate(Csql);
System.out.println("i = " + i);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeTest(conn, st, re);
}
}
//删除数据
static void delete() {
Connection conn = null;
Statement st = null;
ResultSet re = null;
try {
conn = DriverManager.getConnection(url, user, password);
st = conn.createStatement();
int i = st.executeUpdate(Dsql);
System.out.println(" i = " + i);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeTest(conn, st, re);
}
}
//更新数据
static void update() {
Connection conn = null;
Statement st = null;
ResultSet re = null;
try {
conn = DriverManager.getConnection(url, user, password);
st = conn.createStatement();
int i = st.executeUpdate(Usql);
System.out.println("i = " + i);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtil.closeTest(conn, st, re);
}
}
//查找数据
static void read() {
Connection conn = null;
Statement st = null;
ResultSet re = null;
try {
conn = DriverManager.getConnection(url, user, password);
st = conn.createStatement();
re = st.executeQuery(Rsql);
while (re.next()) {
System.out
.println(re.getInt("id") + re.getString("name") + re.getInt("age") + re.getString("birthday"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtil.closeTest(conn, st, re);
}
}
}
2.2、SQLCRUD.java(对上面的例子优化)
优点:
1、解决了SQL注入问题
2、实现了简单的动态操作
package com.jdbc;
import com.jdbc.util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class SQLJdbcTest {
public static void main(String[] args) throws SQLException {
// 计算运行时间
long start = System.currentTimeMillis();
// sqlRead("zhangsan");
// sqlCreate("aaa", 100, new Date("2018/10/20"));
// sqlUpdate("bbb");
sqlDelete("bbb");
long end = System.currentTimeMillis();
System.out.println("所用的时间是:" + (end - start));
}
// 查看指点的数据
static void sqlRead(String name) {
String sql = "select id,name,age,birthday from test where name = ?";
Connection conn = null;
// 解决注入的问题
PreparedStatement ps = null;
ResultSet re = null;
try {
conn = JdbcUtil.getConnection();
// 解决SQL注入问题:实现动态注入
ps = conn.prepareStatement(sql);
// "1" 是指 第一个参数,name是要查的值。既是给占位符赋值
ps.setString(1, name);
// 下面添加sql,如果添加了会报错
re = ps.executeQuery();
while (re.next()) {
System.out.println(re.getInt("id") + "\t" + re.getString("name") + "\t" + re.getInt("age") + "\t"
+ re.getString("birthday"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeTest(conn, ps, re);
}
}
// 增加数据
static void sqlCreate(String name, int age, Date birthday) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet re = null;
try {
String sql = "insert into test(name,age,birthday) values (?,?,?)";
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, age);
// 在util包下new date对象获得他的时间,在传给sql包下的Date。
/*
* ava.util.Date 就是在除了SQL语句的情况下面使用 java.sql.Date
* 是针对SQL语句使用的,它只包含日期而没有时间部分 它都有getTime方法返回毫秒数,自然就可以直接构建。
* java.util.Date 是 java.sql.Date 的父类(注意拼写)
* 前者是常用的表示时间的类,我们通常格式化或者得到当前时间都是用他
* 后者之后在读写数据库的时候用他,因为PreparedStament的setDate()
* 的第2参数和ResultSet的getDate()方法的第2个参数都是java.sql.Date 转换是
* java.sql.Date date=new Java.sql.Date(); java.util.Date d=new
* java.util.Date (date.getTime());
*/
ps.setDate(3, new java.sql.Date(birthday.getTime()));
int i = ps.executeUpdate();
System.out.println("i = " + i);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeTest(conn, ps, re);
}
}
//更新数据
static void sqlUpdate(String name) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet re = null;
try {
String sql = "update test set name=? where id>7";
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, name);
int i = ps.executeUpdate();
System.out.println("i = " + i);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtil.closeTest(conn, ps, re);
}
}
//删除数据
static void sqlDelete(String name) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet re = null;
try {
String sql = "delete from test where name = ?";
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, name);
int i = ps.executeUpdate();
System.out.println("i = " + i);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtil.closeTest(conn, ps, re);
}
}
}