java jdbc 操作数据库_JDBC操作总结

JDBC是一组能够执行SQL语句的API

由于传统的数据库操作方式需要程序员掌握各个不同的数据库的API,极其不便

因此java定义了JDBC这一标准的接口和类,为程序员操作数据库提供了统一的方式

JDBC的操作方式比较单一,由五个流程组成:

1.通过数据库厂商提供的JDBC类库向DriverManager注册数据库驱动

2.使用DriverManager提供的getConnection()方法连接到数据库

3.通过数据库的连接对象的createStatement方法建立SQL语句对象

4.执行SQL语句,并将结果集合返回到ResultSet中

5.使用while循环读取结果

6.关闭数据库资源

下面来看看具体操作Mysql数据库的方法

准备工作

首先我们需要建立一个数据库和一张简单的表

mysql> create databaseperson;

Query OK,1 row affected (0.00sec)

mysql> useperson;Databasechanged

mysql> create tablestudent(-> id int,-> name varchar(20),-> birth year

-> ) default charset=utf8;

Query OK,0 rows affected (0.10 sec)

然后往里面插入几条数据

mysql> insert into student values

-> (1,'张三',1990),-> (2,'李四',1991),-> (3,'王五',1992);

Query OK,3 rows affected (0.02sec)

Records:3 Duplicates: 0 Warnings: 0

这样一张简单的表就建好了

mysql> select * fromstudent;+------+--------+-------+

| id | name | birth |

+------+--------+-------+

| 1 | 张三 | 1990 |

| 2 | 李四 | 1991 |

| 3 | 王五 | 1992 |

+------+--------+-------+

3 rows in set (0.00 sec)

接下来,去mysql官网下载数据库连接器这个包

其中这个包里面含有一份文档,里面列举了基本的使用方法,可以参考

我们的操作也是按照这份文档中的内容进行,然后最主要的地方就是导入这个jar包

32c88c8c8557d48d3ec7106fe6f536c9.png

为了操作方便,这里使用eclipse来导入

右键项目-->构件路径-->添加外部归档,添加好了之后如下所示

ba5eadc3b6f698fab1d1511e3fa41574.png

现在我们正式开始使用java来操作mysql数据库

JDBC操作

实例1:最简单的查询操作

import java.sql.*;public classDemo {//为了代码紧凑性,暂时抛出所有异常

public static void main(String[] args) throwsException {//注册数据库驱动

Class.forName("com.mysql.jdbc.Driver");//建立数据库连接//参数一:jdbc:mysql//地址:端口/数据库,参数二:用户名,参数三:密码

Connection conn =DriverManager.getConnection

("jdbc:mysql://localhost:3306/person","root","admin");//创建SQL语句

Statement st =conn.createStatement();//执行语句,返回结果

ResultSet rt = st.executeQuery("show tables");//循环取出结果

while(rt.next()) {//获取字段

System.out.println(rt.getString("Tables_in_person"));

}//关闭资源,最先打开的最后关

rt.close();

st.close();

conn.close();

}

}

运行结果:student

如此便可执行show tables语句查询出当前数据库含有多少张表

其中rt.getString()方法是获取字段,这点需要注意

关闭资源的方式也与以往相反

不过,上面的操作方式灵活性不大,并且不严谨

实例2:优化的查询操作

importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;public classDemo {public static voidmain(String[] args) {

String url= "jdbc:mysql://localhost:3306/person";

String user= "root";

String pwd= "admin";

String sql= "select * from student";

Connection conn= null;

Statement st= null;

ResultSet rs= null;try{

Class.forName("com.mysql.jdbc.Driver");

conn=DriverManager.getConnection(url,user,pwd);

st=conn.createStatement();//执行查询语句,另外也可以用execute(),代表执行任何SQL语句

rs =st.executeQuery(sql);while(rs.next()) {

System.out.println(rs.getObject(1) + " " +rs.getObject(2) + " " + rs.getInt("birth"));

}//分别捕获异常

} catch(ClassNotFoundException e) {

e.printStackTrace();

}catch(SQLException e) {

e.printStackTrace();

}finally{try{//判断资源是否存在

if(rs != null) {

rs.close();//显示的设置为空,提示gc回收

rs = null;

}if(st != null) {

st.close();

st= null;

}if(conn != null) {

conn.close();

conn= null;

}

}catch(SQLException e) {

e.printStackTrace();

}

}

}

}

运行结果:

cb6775568616126745ea80da75bca669.png

这里把异常给分别捕获了,并且相关的字符串全部用变量定义

需要注意下循环取出数据里面的getInt()方法,此处必须知道类型和字段才能取出

如果不知道可以使用getObject(1)取出第一列,getObject(2)取出第二列,以此类推

实例3:自定义变量插入到数据库

importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;importjava.sql.Statement;public classDemo {public static voidmain(String[] args) {//参数检查

if (args.length != 3) {

System.out.println("参数形式不对");

System.exit(0);

}

String id= args[0];

String name= args[1];

String birth= args[2];

String sql= "insert into student values(" + id + ",'" + name +

"'," + "'" + birth + "')";

System.out.println(sql);

String url= "jdbc:mysql://localhost:3306/person";

String user= "root";

String pwd= "admin";

Connection conn= null;

Statement st= null;try{

Class.forName("com.mysql.jdbc.Driver");

conn=DriverManager.getConnection(url,user,pwd);

st=conn.createStatement();//注意,此处是excuteUpdate()方法执行

st.executeUpdate(sql);//分别捕获异常

} catch(ClassNotFoundException e) {

e.printStackTrace();

}catch(SQLException e) {

e.printStackTrace();

}finally{try{if(st != null) {

st.close();

st= null;

}if(conn != null) {

conn.close();

conn= null;

}

}catch(SQLException e) {

e.printStackTrace();

}

}

}

}

运行结果:

2ed0102ca1c61c6e702d37083ea326e5.png

这里运行需要设置自变量,窗口中右键-->运行方式-->运行配置

然后在自变量里面写4 susan 1993,我没有写中文,因为产生乱码,目前还不清楚原因

需要注意的是,执行插入的SQL语句比较难写,最好是打印出SQL语句用以检查

实例4:PreparedStatement应用

从上面的Demo可以看到,插入数据的时候,SQL操作相当不便

这里可以使用PreparedStatement对象来简化SQL语句的建立

importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;public classDemo {public static voidmain(String[] args) {if (args.length != 3) {

System.out.println("参数形式不对");

System.exit(0);

}

String id= args[0];

String name= args[1];

String birth= args[2];

String url= "jdbc:mysql://localhost:3306/person";

String user= "root";

String pwd= "admin";

Connection conn= null;//声明PreparedStatement对象的引用

PreparedStatement pst = null;try{

Class.forName("com.mysql.jdbc.Driver");

conn=DriverManager.getConnection(url,user,pwd);//使用?代替变量

pst = conn.prepareStatement("insert into student values (?,?,?)");//给指定参数的位置设定变量

pst.setString(1, id);

pst.setString(2, name);

pst.setString(3, birth);

pst.executeUpdate();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}catch(SQLException e) {

e.printStackTrace();

}finally{try{if(pst != null) {

pst.close();

pst= null;

}if(conn != null) {

conn.close();

conn= null;

}

}catch(SQLException e) {

e.printStackTrace();

}

}

}

}

运行结果:

212b73a58e857ba5dd12980fa75c2cf9.png

实例5:Batch批处理

importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;importjava.sql.Statement;public classDemo {public static voidmain(String[] args) {

String url= "jdbc:mysql://localhost:3306/person";

String user= "root";

String pwd= "admin";

Connection conn= null;

Statement st= null;try{

Class.forName("com.mysql.jdbc.Driver");

conn=DriverManager.getConnection(url,user,pwd);

st=conn.createStatement();//添加批处理

st.addBatch("insert into student values(6,'Jerry','1995')");

st.addBatch("insert into student values(7,'Greg','1996')");

st.addBatch("insert into student values(8,'Ryan','1997')");//执行批处理

st.executeBatch();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}catch(SQLException e) {

e.printStackTrace();

}finally{try{if(st != null) {

st.close();

st= null;

}if(conn != null) {

conn.close();

conn= null;

}

}catch(SQLException e) {

e.printStackTrace();

}

}

}

}

运行结果:

510c7f2d04c873cc9b646ee69d4f2d92.png

批处理比较简单,只需先建立Statement对象,然后逐个添加批处理即可

最后使用executeBatch()方法执行批处理

此外,PreparedStatement对象也可以使用批处理

PreparedStatement ps = conn.prepareStatement("insert into student values(?,?,?)");

ps.setInt(1,8);

ps.setString(2,"GG");

ps.setString(3,"1996");

ps.addBatch();

ps.executeBatch();

实例6:Transaction事务处理

事务处理是要求sql以单元的形式更新数据库,要求其确保一致性

如银行的转账业务,一方转出后,另一方则增加

如果出现异常,那么所有的操作则会回滚

importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;importjava.sql.Statement;public classDemo {public static voidmain(String[] args) {

String url= "jdbc:mysql://localhost:3306/person";

String user= "root";

String pwd= "admin";

Connection conn= null;

Statement st= null;try{

Class.forName("com.mysql.jdbc.Driver");

conn=DriverManager.getConnection(url,user,pwd);//取消自动提交

conn.setAutoCommit(false);

st=conn.createStatement();

st.addBatch("insert into student values(6,'Jerry','1995')");

st.addBatch("insert into student values(7,'Greg','1996')");

st.addBatch("insert into student values(8,'Ryan','1997')");

st.executeBatch();//提交后设置自动提交

conn.commit();

conn.setAutoCommit(true);

}catch(ClassNotFoundException e) {

e.printStackTrace();

}catch(SQLException e) {

e.printStackTrace();if(conn != null) {try{//出现异常则回滚操作,然后设置自动提交

conn.rollback();

conn.setAutoCommit(true);

}catch(SQLException e1) {

e1.printStackTrace();

}

}

}finally{try{if(st != null) {

st.close();

st= null;

}if(conn != null) {

conn.close();

conn= null;

}

}catch(SQLException e) {

e.printStackTrace();

}

}

}

}

运行结果:

0aab8adb9decc73f6a3ea7557967fafb.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值