一、步骤
- 1.获取数据库链接
- 2.创建Statement对象
- 3.编写SQL语句
- 4.executeUpdata更新或executeQuery查询
二、代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20//这里利用上篇文章写好的数据库连接类,并以插入为例
public void Insert(){
Connection conn=null;
Statement st=null;
try{
conn=getConnection();//获取数据库链接
st=conn.createStatement();//创建statement对象
String sql="INSERT INTO STUDENT(no,name,age)VALUES(1,"zx",20)";
st.executeUpdata(sql);//更新数据库
}catch(Exception e){
}finally{
if(st!=null)
st.close();
if(conn!=null)
conn.close();
}
}
三、编写一个通用的关闭连接的类和获取链接的类以及一个通用的数据库更新类
1.获取链接和关闭连接的工具类1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45public class ToolOfDB
{
//获取链接
public static Connection getConnection()throws Exception{
String driverClass=null;
String user=null;
String password=null;
String url=null;
//读取文件
InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(in);
driverClass=properties.getProperty("driver");
user=properties.getProperty("user");
password=properties.getProperty("password");
url=properties.getProperty("url");
Driver driver=(Driver)Class.forName(driverClass).newInstance();//反射机制导入驱动
Properties info=new Properties();
info.put("user",user);
info.put("password",password);
Connection conn=driver.connection(url,info);
return conn;
}
//关闭数据库连接
public static void relaseResource(Statement st,Connection conn){
try{
if(st!=null)
st.close();
}catch(Exception e){
}
try{
if(conn!=null)
conn.close();
}catch(Exception e){
}
}
}
2.DB通用更新类1
2
3
4
5
6
7
8//针对Updata Insert Delete
public static void update(String sql)throws Exception{
Connection conn=ToolOfDB.getConnection();//获取数据库连接
Statement st=conn.createStatement();//创建statement对象
st.executeUpdata(sql);//执行sql语句
ToolofDB.relaseResource(st,conn);//关闭连接释放资源
}
四、小结
上面的代码还可以优化,并且也可以改成相应的动态执行的SQL语句。