您的位置:首页 > 数据库

JDBC 操作数据库的开发步骤

2017-05-02 15:49 267 查看
1、加载数据库驱动并建立到数据库的连接:

try{
//加载MySql的驱动类
Class.forName("com.mysql.jdbc.Driver") ;
}catch(ClassNotFoundException e){
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace() ;
}
String url = "jdbc:mysql://localhost:3306/test" ;
String username = "root" ;
String password = "123456" ;
try{
Connection con =
DriverManager.getConnection(url , username , password ) ;
}catch(SQLException se){
System.out.println("数据库连接失败!");
se.printStackTrace() ;
}


2、执行SQL语句:

1>PreparedStatement用于处理动态SQL语句,在执行前会有一个预编译过程,这个过程是有时间开销的,虽然相对数据库的操作,该时间开销可以忽略不计,但是PreparedStatement的预编译结果会被缓存,下次执行相同的预编译语句时,就不需要编译,只要将参数直接传入编译过的语句执行代码中就会得到执行,所以,对于批量处理可以大大提高效率。

2>Statement每次都会执行SQL语句,相关数据库都要执行SQL语句的编译。

3>作为开发者,应该尽可能以PreparedStatement代替Statement


Statement statement=(Statement) dUtil.getConnection().createStatement();

String sql="delete from diary where title="+"'"+title+"'";

int count=statement.executeUpdate(sql);

System.out.println("删除成功");

String sql="insert into diary(title,content,authorname,time) values(?,?,?,now())";
try {
PreparedStatement preparedStatement=(PreparedStatement) dUtil.getConnection().prepareStatement(sql);
String title=diary.getTitle();
String content=diary.getContent();
String authorname=diary.getAuthorName();
preparedStatement.setString(1, title);
preparedStatement.setString(2, content);
preparedStatement.setString(3, authorname);
}catch(Exception se){
se.printStackTrace() ;
}


3、处理结果:

ResultSet resultSet=statement.executeQuery(sql);
while (resultSet.next()) {
Diary diary=new Diary();
diary.setAuthorName(resultSet.getString("authorname"));
diary.setContent(resultSet.getString("content"));
diary.setTitle(resultSet.getString("title"));
diary.setId(resultSet.getInt("id"));
Date time=resultSet.getDate("time");
}


4、从数据库断开连接释放资源:

public static void closeConnection(ResultSet resultSet,PreparedStatement preparedStatement, Connection connection) throws SQLException {

if (resultSet!=null) resultSet.close();
if (preparedStatement!=null) preparedStatement.close();
if(connection!=null&&connection.isClosed()==false) connection.close();
System.out.println("数据库关闭");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdbc