jdbc基础 (一) MySQL的简单使用

时间:2022-05-08
本文章向大家介绍jdbc基础 (一) MySQL的简单使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前段时间学习了jdbc,正好利用这几篇文章总结一下。

JDBC 可做三件事:与数据库建立连接、发送操作数据库的语句并处理结果。

而程序首先要做的就是加载数据库驱动,这里我使用的是mysql:

1 String driverName=new String("com.mysql.jdbc.Driver");
2 Class.forName(driverName);

然后再获取数据库连接对象,参数为数据库的url,用户名以及密码。这里我使用的数据库名为jdbc,用户名为root,密码为123456:

1 String url=new String("jdbc:mysql://localhost:3306/jdbc");
2 String user=new String("root");
3 String password=new String("123456");
4 Connection coon=DriverManager.getConnection(url, user, password);

因为要对数据库进行操作,所以要获取Statement对象:

1 Statement statement = connection.createStatement();

statement对象内封装的execute(String sql)方法以及executeQuery(String sql)方法和executeUpdate(String sql)方法可以用来执行sql语句,以此来实现对数据库的操作。

 1   String sql = null;
 2   ResultSet resultSe = null;
 3 
 4   //创建Student表
 5   sql="create table Student (id char(9) primary key,name char(9) unique)";
 6   statement.execute(sql);        
 7          
 8   //添加元组
 9   sql = "insert into Student (id,name) values ('0001','zhangsan')";
10   statement.executeUpdate(sql);
11          
12   //查询Student表
13   sql="select * from Student";
14   resultSet = statement.executeQuery(sql);
15             
16   while(resultSet.next()){
17       System.out.println("name:"+resultSet.getString("name"));
18       System.out.println("id:"+resultSet.getString("id"));
19   }
20  
21   //删除元组
22   sql="delete from Student where id='0001'";
23   statement.executeUpdate(sql);
24  
25   //删除表Student
26   sql="drop table Teacher";
27   statement.execute(sql);    

操作完数据库之后要关闭资源,顺序依次为resultSet,statement,connection:

 1 try {
 2     if (resultSet != null)
 3         resultSet.close();
 4  } catch (SQLException e) {
 5        e.printStackTrace();
 6  } finally {
 7        resultSet = null;
 8        try {
 9            if (statement != null)
10              statement.close();
11        } catch (SQLException e) {
12              e.printStackTrace();
13        } finally {
14              statement = null;
15              try {
16                  if (connection != null)
17                     connection.close();
18              } catch (SQLException e) {
19                     e.printStackTrace();
20              } finally {
21                     connection = null;
22              }
23         }
24  }

close()会抛出异常,需要try/catch语句块。为保证资源的释放,需要将close()方法的调用放在finally语句块里,释放资源前判断对象是否为null。至此,利用jdbc连接数据库进行简单的操作算是完成了。