JDBC简介与使用
什么是JDBC
JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java
API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
数据库驱动
我们安装好数据库之后,我们的应用程序也是不能直接使用数据库的,必须要通过相应的数据库驱动程序,通过驱动程序去和数据库打交道。其实也就是数据库厂商的JDBC接口实现,即对Connection等接口的实现类的jar文件。
下载驱动
**推荐下载地址:**https://mvnrepository.com/artifact/mysql/mysql-connector-java
搭建实验环境
- 新建一个Java工程,并导入数据驱动。
- 在mysql中创建一个库,并创建user表和插入表的数据。
使用JDBC
编写程序从user表中读取数据,并打印在命令行窗口中
编写JDBC代码的固定步骤
1.加载驱动
2.获取与数据库的连接
3.获取用于向数据库发送sql语句的statement
4.向数据库发sql,并获取代表结果的resultset
5.取出结果集的数据
6.关闭连接,释放资源
DriverManager类
Jdbc程序中的DriverManager用于加载驱动,并创建与数据库的链接,这个API的常用方法:
1.DriverManager.registerDriver(newDriver());
2.DriverManager.getConnection(url,user,password)
注意:在实际开发中并不推荐采用registerDriver方法注册驱动。原因有两个:
1.查看Driver的源码可以看到,如果采用此种方式,会导致驱动程序注册两次,在内存中会有两个Driver对象
2.程序依赖mysql的api,脱离mysql的jar包,程序将无法编译,将来程序切换底层数据库将会非常麻烦
推荐方式:Class.forName(“com.mysql.jdbc.Driver”);
采用此种方式不会导致驱动对象在内存中重复出现,并且采用此种方式,程序仅仅只需要一个字符串,不需要依赖具体的驱动,使程序的灵活性更高
数据库URL
URL用于标识数据库的位置,通过URL地址告诉JDBC程序连接哪个数据库,URL的写法为:
dbc:mysql://localhost:3306/test?参数名:参数值
依次为:协议+子协议+主机:端口+数据库+参数
常用数据库URL地址的写法:
-
Oracle写法:
jdbc:oracle:thin:@localhost:1521:sid
-
SqlServer写法jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=sid
-
MySql写法:
jdbc:mysql://localhost:3306/sid
如果连接的是本地的Mysql数据库,并且连接使用的端口是3306
那么的url地址可以简写为:jdbc:mysql:///数据库
常用接口
1.Driver接口
Driver接口由数据库厂家提供,作为java开发人员,只需要使用Driver接口就可以了。在编程中要连接数据库,必须先装载特定厂商的数据库驱动程序,不同的数据库有不同的装载方法。如:
装载MySql驱动:Class.forName(“com.mysql.jdbc.Driver”);
装载Oracle驱动:Class.forName(“oracle.jdbc.driver.OracleDriver”);
2.Connection接口
Connection与特定数据库的连接(会话),在连接上下文中执行sql语句并返回结果。DriverManager.getConnection(url, user, password)方法建立在JDBC URL中定义的数据库Connection连接上。
连接MySql数据库:Connection conn = DriverManager.getConnection(“jdbc:mysql://host:port/database”, “user”, “password”);
连接Oracle数据库:Connection conn = DriverManager.getConnection(“jdbc:oracle:thin:@host:port:database”, “user”, “password”);
连接SqlServer数据库:Connection conn = DriverManager.getConnection(“jdbc:microsoft:sqlserver://host:port; DatabaseName=database”, “user”, “password”);
常用方法:
- createStatement():创建向数据库发送sql的statement对象。
- prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象。
- prepareCall(sql):创建执行存储过程的callableStatement对象。
- setAutoCommit(boolean autoCommit):设置事务是否自动提交。
- commit() :在链接上提交事务。
- rollback() :在此链接上回滚事务。
3.Statement接口
用于执行静态SQL语句并返回它所生成结果的对象。
三种Statement类:
- Statement:由createStatement创建,用于发送简单的SQL语句(不带参数)。
- PreparedStatement :继承自Statement接口,由preparedStatement创建,用于发送含有一个或多个参数的SQL语句。PreparedStatement对象比Statement对象的效率更高,并且可以防止SQL注入,所以我们一般都使用PreparedStatement。
- CallableStatement:继承自PreparedStatement接口,由方法prepareCall创建,用于调用存储过程。
常用Statement方法:
- execute(String sql):运行语句,返回是否有结果集
- executeQuery(String sql):运行select语句,返回ResultSet结果集。
- executeUpdate(String sql):运行insert/update/delete操作,返回更新的行数。
- addBatch(String sql) :把多条sql语句放到一个批处理中。
- executeBatch():向数据库发送一批sql语句执行。
4.ResultSet接口
ResultSet提供检索不同类型字段的方法,常用的有:
- getString(int index)、getString(String columnName):获得在数据库里是varchar、char等类型的数据对象。
- getFloat(int index)、getFloat(String columnName):获得在数据库里是Float类型的数据对象。
- getDate(int index)、getDate(String columnName):获得在数据库里是Date类型的数据。
- getBoolean(int index)、getBoolean(String columnName):获得在数据库里是Boolean类型的数据。
- getObject(int index)、getObject(String columnName):获取在数据库里任意类型的数据。
ResultSet还提供了对结果集进行滚动的方法:
- next():移动到下一行
- Previous():移动到前一行
- absolute(int row):移动到指定行
- beforeFirst():移动resultSet的最前面。
- afterLast() :移动到resultSet的最后面。
使用后依次关闭对象及连接:ResultSet → Statement → Connection
创建执行SQL语句的statement创建执行SQL语句的statement
1 //Statement
2 String id = "5";
3 String sql = "delete from table where id=" + id;
4 Statement st = conn.createStatement();
5 st.executeQuery(sql);
6 //存在sql注入的危险
7 //如果用户传入的id为“5 or 1=1”,那么将删除表中的所有记录
1 //PreparedStatement 有效的防止sql注入(SQL语句在程序运行前已经进行了预编译,当运行时动态地把参数传给PreprareStatement时,即使参数里有敏感字符如 or '1=1'也数据库会作为一个参数一个字段的属性值来处理而不会作为一个SQL指令)
2 String sql = “insert into user (name,pwd) values(?,?)”;
3 PreparedStatement ps = conn.preparedStatement(sql);
4 ps.setString(1, “col_value”); //占位符顺序从1开始
5 ps.setString(2, “123456”); //也可以使用setObject
6 ps.executeQuery();
处理执行结果(ResultSet)
1 ResultSet rs = ps.executeQuery();
2 While(rs.next()){
3 rs.getString(“col_name”);
4 rs.getInt(1);
5 //…
6 }
释放资源
//数据库连接(Connection)非常耗资源,尽量晚创建,尽量早的释放
//都要加try catch 以防前面关闭出错,后面的就不执行了
1 try {
2 if (rs != null) {
3 rs.close();
4 }
5 } catch (SQLException e) {
6 e.printStackTrace();
7 } finally {
8 try {
9 if (st != null) {
10 st.close();
11 }
12 } catch (SQLException e) {
13 e.printStackTrace();
14 } finally {
15 try {
16 if (conn != null) {
17 conn.close();
18 }
19 } catch (SQLException e) {
20 e.printStackTrace();
21 }
22 }
23 }
案列
public class Trst3 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1加载驱动
Class.forName ("com.mysql.jdbc.Driver");
//2获取数据库的链接
String username="root";
String password="123456";
String url="jdbc:mysql://localhost:3306/jdbcstudy";
Connection connection=DriverManager.getConnection (url,username,password);
//3编写MySQL语句
Statement statement=connection.createStatement ();
String sql="select id,name,password,email from users";
ResultSet resultSet=statement.executeQuery (sql);
while (resultSet.next ()){
System.out.println (resultSet.getObject ("id") );
System.out.println (resultSet.getObject ("name") );
System.out.println (resultSet.getObject ("password") );
System.out.println (resultSet.getObject ("email") );
}
//释放资源
resultSet.close ();
statement.close ();
connection.close ();
}
}
statement对象介绍
-
Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可
-
Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变
化)
-
Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象
CRUD操作-create
CRUD操作-update
CRUD操作-delete
CRUD操作-read
优化实验环境
利用properties存储数据库信息
driver = com.mysql.jdbc.Driver
username = root
password = 123456
url = jdbc:mysql://localhost:3306/jdbcstudy?useSSL=true
编写一个工具类负责创建连接和关闭数据库资源
public class JDBCUtlils {
private static String driver=null;
private static String username=null;
private static String password=null;
private static String url=null;
static{
try {
//加载配置文件
InputStream is = JDBCUtlils.class.getClass ().getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(is);
//读取配置文件
driver = properties.getProperty("driver");
username = properties.getProperty("username");
password = properties.getProperty("password");
url = properties.getProperty("url");
//加载数据库驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取数据库连接对象
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//释放资源
public static void closeAll(ResultSet resultSet, Statement statement,Connection connection){
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
利用Junit测试增删改查
public class Deme1 {
//测试JDBC的CRUD
@Test
public void insert() {
Connection connection = null;
Statement statement = null;
try {
//1.获取数据库连接
connection = JDBCUtlils.getConnection ( );
//2.创建statement对象
statement = connection.createStatement ( );
//3.编写Sql语句
String sql = "INSERT INTO users(id,NAME,PASSWORD,email,birthday) VALUES(5,'wangwu','123456','wangwu@sina.com','1979-12-04');";
//4.执行sql语句
int i = statement.executeUpdate (sql); //返回受影响的行数
} catch (SQLException e) {
e.printStackTrace ( );
} finally {
//5.释放资源
JDBCUtlils.closeAll (null, statement, connection);
}
}
@Test
public void delete() {
Connection connection = null;
Statement statement = null;
try {
//1.获取数据库连接
connection = JDBCUtlils.getConnection ( );
//2.创建statement对象
statement = connection.createStatement ( );
//3.编写Sql语句
String sql = "delete from users where id = 4";
//4.执行sql语句
int i = statement.executeUpdate (sql); //返回受影响的行数
if (i > 0) {
System.out.println ("删除成功");
}
} catch (SQLException e) {
e.printStackTrace ( );
} finally {
//5.释放资源
JDBCUtlils.closeAll (null, statement, connection);
}
}
@Test
public void update() {
Connection connection = null;
Statement statement = null;
try {
//1.获取数据库连接
connection = JDBCUtlils.getConnection ( );
//2.创建statement对象
statement = connection.createStatement ( );
//3.编写Sql语句
String sql = "update users set name = 'xiaohong' where id = 4";
//4.执行sql语句
int i = statement.executeUpdate (sql); //返回受影响的行数
if (i > 0) {
System.out.println ("修改成功");
}
} catch (SQLException e) {
e.printStackTrace ( );
} finally {
//5.释放资源
JDBCUtlils.closeAll (null, statement, connection);
}
}
@Test
public void query() {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//1.获取数据库连接
connection = JDBCUtlils.getConnection ( );
//2.创建statement对象
statement = connection.createStatement ( );
//3.编写Sql语句
String sql = "select * from users";
//4.执行sql语句
resultSet = statement.executeQuery (sql);
while (resultSet.next ( )) {
System.out.println (resultSet.getInt ("id"));
System.out.println (resultSet.getString ("name"));
System.out.println (resultSet.getString ("password"));
System.out.println (resultSet.getString ("email"));
System.out.println (resultSet.getDate ("birthday"));
}
} catch (SQLException e) {
e.printStackTrace ( );
} finally {
//5.释放资源
JDBCUtlils.closeAll (resultSet, statement, connection);
}
}
}