实现加载驱动、得到数据库对象、关闭资源的代码复用,将代码提取到相应的工具包里边。优化程序
工具包
package com.xxx;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 工具类
*
*/
public class Connectiontools {
public static Connection getConn() {
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;databaseName=test";
String username = "zheng";
String pwd = "123";
conn = DriverManager.getConnection(url, username, pwd);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
// 关闭修改操作
public static void close(Statement stmt, Connection conn) {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 关闭插入、插入等操作
public static void close(Statement stmt, ResultSet rs, Connection conn) {
try {
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
实现的操作
package com.xxx;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StatementDemo1 {
private Connection conn = null;
private Statement stmt = null;
private ResultSet result = null;
// 查询员工信息
public void query() {
// 1、加载驱动
try {
conn = Connectiontools.getConn();
stmt = conn.createStatement();
// 查询信息
String selectstr = "select *from info";
result = stmt.executeQuery(selectstr);
// 4、处理结果集
System.out.println("员工编号:\t员工姓名:\t工作:");
while (result.next()) {
System.out.println(result.getString("id") + "\t" + result.getString("name") + "\t" + "\t"
+ result.getString("job"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源
Connectiontools.close(stmt, result, conn);
}
}
// 修改信息
public void update() {
try {
// 1、加载驱动
conn = Connectiontools.getConn();
// 2、创建statement
stmt = conn.createStatement();
// 3、创建sql语句
String updatestr = "update info set job='教授 ' where id='001'";
int result = stmt.executeUpdate(updatestr);
// 4、处理结果集
if (result > 0) {
System.out.println("更新成功!!!");
} else {
System.out.println("更新失败!!!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
Connectiontools.close(stmt, conn);
}
}
public static void main(String[] args) {
StatementDemo1 c = new StatementDemo1();
c.query();
}
}