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

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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 //删除表Student26 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连接数据库进行简单的操作算是完成了。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航