title: "Jdbc"
date: 2019-08-14T11:03:49+08:00
draft: true
本章内容为:《JDBC基础》
作者:nuoccc
这篇文章 主要是进行jdbc的基础代码讲解,学习jdbc基础。
首先来了解一下什么是jdcb
1.JDBC的概念
JDBC(Java Data Base Connectivity, java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。是Java访问数据库的标准规范。SUN公司提供的一套连接并操作数据库的一种技术!!
JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
2.JDBC 驱动
Java提供访问数据库规范称为JDBC,而生产厂商提供规范的实现类称为驱动。
负责连接不同类型的数据库,JAVA连接不同的数据库,需要导入对应数据库的驱动包!
JDBC是接口,驱动是接口的实现,没有驱动将无法完成数据库连接,从而不能操作数据库!每个数据库厂商都需要提供自己的驱动,用来连接自己公司的数据库,也就是说驱动一般都由数据库生成厂商提供。
3.创建JDBC程序进行查询
首先先准备好我们数据库连接上的表
create database testjdbc;
-- 创建一个名为testjdbc的数据库
use testjdbc;
-- 使用这个数据库
create table testTable(
uid int(4) primary key auto_increment,
uname varchar(20) not null,
uage int(4) not null,
usex varchar(10) not null,
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 创建一个测试表 ,拥有用户id,用户名,用户年龄,以及用户性别四个属性。
insert into testTable values(null,'张三',20,'男');
insert into testTable values(null,'李四',24,'男');
insert into testTable values(null,'赵舞',22,'女');
-- 随便插入几条测试数据
这样一张测试表就创好了,然后来进行我们的代码编写,别忘了导入相应数据库的驱动!、
public void main(String[] args){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
}
首先创立以上三个类的对象,然后我们再来了解一下这三个类是什么。
-
Connection类
connection类的作用是与数据库建立连接,数据库与客户端的交互都是通过connection对象完成的。
connection常用方法,我们进Connection接口看下声明的一些方法:
1.Statement createStatement() throws SQLException;
Creates a <code>Statement</code> object for sending SQL statements to the database.
这是类中对这个方法的描速,创建一个Statement对象用来发送SQL命令到数据库。
2.PreparedStatement prepareStatement(String sql) throws SQLException;
Creates a PreparedStatement object for sending parameterized SQL statements to the database.
pre-compiled and stored in a <code>PreparedStatement</code> object. This object can then be used to efficiently execute this statement multiple times.
这是类中对这个方法的描速,创建一个PrepareStatement对象来传递一个sql命令参数给数据库。
会预编译存储在PrepareStatement对象中,这个对象之后能被更有效地执行这个sql语句多次。
3.CallableStatement prepareCall(String sql) throws SQLException;
Creates a <code>CallableStatement</code> object for calling database stored procedures.The <code>CallableStatement</code> object provide methods for setting up its IN and OUT parameters, and methods for executing the call to a stored procedure.
这是类中对这个方法的描速,创建一个CallableStatement对象来调用数据库存储过程。CallableStatement对象提供了设置其IN和OUT参数的方法,以及执行对存储过程的调用的方法。
4.void setAutoCommit(boolean autoCommit) throws SQLException;
Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either the method
<code>commit</code> or the method <code>rollback</code>.By default, new connections are in auto-commitmode.
这是类中对这个方法的描速,将此连接的自动提交模式设置为给定状态。如果一个连接处于自动提交模式,那么它的所有SQL语句都将作为单独的事务执行和提交。否则,它的SQL语句将被分组到事务中,这些事务将通过调用其中一个方法来终止commit或方法rollback。默认情况下,新连接处于自动提交模式。
5.void commit() throws SQLException;
Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this <code>Connection</code> object. This method should be used only when auto-commit mode has been disabled.
这是类中对这个方法的描速,对上次提交/回滚以来所做的进行更改,并释放当前由该Connection对象持有的任何数据库锁。只有在禁用自动提交模式时才应使用此方法。
6.void rollback() throws SQLException;
Undoes all changes made in the current transaction and releases any database locks currently held by this <code>Connection</code> object. This method should be used only when auto-commit mode has been disabled.
这是类中对这个方法的描速,撤消当前事务中所做的所有更改,并释放此Connection对象当前持有的任何数据库锁。只有在禁用自动提交模式时才应使用此方法。
这些就是Connection接口中我们常用的一些方法,然后我们再来了解Statement类
-
Statement类
statement类用于执行静态SQL语句的对象并返回它生成的结果。
然后我们来看下Statement接口常用的一些方法声明:
1.ResultSet executeQuery(String sql) throws SQLException;
Executes the given SQL statement, which returns a single <code>ResultSet</code> object.
执行给定的SQL语句,该语句返回一个ResultSet对象。通常用于查询。
2.int executeUpdate(String sql) throws SQLException;
Executes the given SQL statement, which may be an <code>INSERT</code>, <code>UPDATE</code>, or <code>DELETE</code> statement or an SQL statement that returns nothing, such as an SQL DDL statement.
执行给定的SQL语句,该语句可以是INSERT,UPDATE,或DELETE语句或不返回任何结果的SQL语句,如SQL DDL语句。
3.void addBatch( String sql ) throws SQLException;
Adds the given SQL command to the current list of commands for this <code>Statement</code> object. The commands in this list can beexecuted as a batch by calling the method <code>executeBatch</code>.
将给定的SQL命令添加到此语句对象的当前命令列表中。这个列表中的命令可以通过调用方法executeBatch作为批处理执行。
4.int[] executeBatch() throws SQLException;
Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.If one of the commands in a batch update fails to execute properly,
this method throws a <code>BatchUpdateException</code>, and a JDBC driver may or may not continue to process the remaining commands in the batch.
向数据库提交一批命令以便执行,如果所有命令都成功执行,则返回更新计数数组。如果批处理更新中的一个命令不能正确执行,该方法将抛出BatchUpdateException, JDBC驱动程序可能继续处理批处理中的剩余命令,也可能不继续处理。
最后我们再来了解一下什么是ResultSet
-
ResultSet
表示数据库结果集合的数据表,通常由执行查询数据库的语句生成。
A <code>ResultSet</code> object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The <code>next</code> method moves the cursor to the next row, and because it returns <code>false</code> when there are no more rows in the <code>ResultSet</code> object, it can be used in a <code>while</code> loop to iterate through the result set.
一个ResultSet对象维护一个指向其当前数据行的指针。最初,光标定位在第一行之前。next方法将光标移动到下一行,由于它返回false,当ResultSet对象中没有更多行时,它可以在中使用,而循环遍历结果集。
所以我们在ResultSet中常用的也是next()方法来遍历这个集合。
然后我们来继续我们的代码
public void main(String[] args){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testjdbc?useUnicode=true&characterEncoding=utf-8", "root", "123");
}
这里我们来了解一下DriverManager类
-
DriverManager类
DriverManager是驱动管理类,Jdbc程序中的DriverManager用于加载驱动,并创建与数据库的链接,这个API的常用方法:
1.DriverManager.registerDriver(new Driver())
参数:Driver--来自于你要连接的数据库(如果连接orcale,来自于oracle如果要连接mysql,来自于mysql)
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
注意:在实际开发中并不推荐采用registerDriver方法注册驱动。
原因有二:
1、查看Driver的源代码可以看到,如果采用此种方式,会导致驱动程序注册两次,也就是在内存中会有两个Driver对象(因为在mysql中的Driver中有静态代码块,已经注册了)。
2、程序依赖mysql的api,脱离mysql的jar包,程序将无法编译,将来程序切换底层数据库将会非常麻烦。
推荐方式:
Class.forName("com.mysql.jdbc.Driver");
会把com.mysql.jdbc.Driver中的静态代码块执行一次。会实现驱动的注册。把指定的类加载到内存中!
2.DriverManager.getConnection(url, user, password)
建立与数据库的连接
参数:
url:连接到某一个具体的数据库
user:数据库的用户名
password:数据库用户名对应的密码。
URL用于标识数据库的位置,通过URL地址告诉JDBC程序连接哪个数据库,URL的写法为:
了解完DriverManager类之后我们继续
public void main(String[] args){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");//导入mysql驱动
conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testjdbc?useUnicode=true&characterEncoding=utf-8", "root", "123");
//获得跟数据库的连接
st=conn.createStatement();//接受创建的Statement对象
String sql = "select * from testtable";//查询表中所有内容
rs=st.executeQuery(sql);//executeQuery()返回一个ResultSet对象,所以接受这个对象
System.out.println("编号\t姓名\t年龄\t性别");
while (rs.next()) {
int id = rs.getInt("uid"); // 表中字段不区分大小写,根据列名获取对应的值
String name = rs.getString("uname");
int age = rs.getInt("uage");
String sex = rs.getString("usex");
System.out.println(id+"\t\t"+name+"\t"+age+"\t\t"+sex);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
// 关闭流
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
}
}
这样一个jdbc最基础的读取(Read)也就完成了。
jdbc有四个操作CRUD,学完了R,我们再进行CUD的操作。
4.JDBC新增数据/更新数据/删除数据(Create/Update/Delete)
为什么我要把这三个放一起呢?因为Statement对象的新增/更新/删除都是用的executeUpdate()方法,
只是执行的sql语句不同,其他都是相同的,所以直接放一起。
public void main(String[] args){
Connction con = null;
Statement st = null;//首先先创立Connction 和 Statement的引用
Class.forName("com.mysql.jdbc.Driver");
//加载mysql驱动
con=DriverManger.getConnection("jdbc:mysql://127.0.0.1:3306/testjdbc?useUnicode=true&characterEncoding=utf-8", "root", "123");
//获得Connection对象
st=con.createStatement();
//获得Statement对象
String sql = "insert into testtable values(null,'李四',20,'男')";
//因为是新增 所以数据库语言是插入语言,向我们的testtable表插入数据。
/*
String sql = "Update set testtable name = '赵六' where id =2";
数据库更新语言,把id等于2时的名字改成赵六
String sql = "Delete from testtable where id=2"
把id等于2的这条记录删除
*/
int count = st.executeUpdate(sql);
//执行数据库新增/更新/删除语言,返回值 成功为1,不成功为0。
if(count>0){
System.out.println("新增成功!");
}else{
System.out.println("新增失败");
}
st.close();
con.close();
//关闭连接,然后这些代码中我没加入try catch,请自行加入。
}
这样JDBC基础的CRUD就完成了,JDBC基础就到这,加深JDBC运用可以看看《JDBC基础2》。