JDBC操作数据库的编程步骤

//第一步,注册驱动程序

Class.forName( “数据库驱动的完整类名”);

//第二步,获取一个数据库的连接

Connection conn=DriverManager.getConnection("连接URL","用户名","密码");

//第三步,创建一个会话

Statement stmt=conn.createStatement();

//第四步,执行SQL语句,增加、删除、修改记录。

stmt.executeUpdate(“增加、删除、修改记录的SQL语句”);

//或者查询记录

ResultSet rs=stmt.executeQuery(“查询记录的SQL语句”);

//第五步,对查询的结果进行处理

while(rs.next()){

...//对记录的操作

}

//第六步,关闭连接

rs.close()

stmt.close();

conn.close();

//代码

package jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * 创建JDBC连接
 * @author Yikong
 *
 */
public class JdbcDao {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接
private Connection getConn(){
try {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/kiwiPlus","root","root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//释放资源
private  void release(ResultSet rs,Statement ps,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public User getUserById(String id){
ResultSet rs=null;
PreparedStatement ps=null;
Connection conn=null;
String sql="select * from user where id=?";//SQL语句
try {
conn=this.getConn();
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
if(rs!=null){
//如果存在,则直接构建并返回用户对象
User user=new User(rs.getString("id"),rs.getString("name"),rs.getString("gender"));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
this.release(rs, ps, conn);
}
return null;
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章