下列是连接sqlserver数据库的 如果是mysql的话把连接驱动和连接路径需要换成:
// 连接驱动
private static final String DRIVER="com.mysql.jdbc.Driver";
// 连接路径
private static final String URL ="jdbc:mysql://localhost:3306/XXX";
import java.sql.*;
/**
* 数据库连接工具类
*/
public class DataBaseConnectionUtil {
// 连接驱动
private static final String DRIVER= "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 连接路径
private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=XXX";
// 用户名
private static final String USERNAME = "sa";
// 密码
private static final String PASSWORD = "123456";
//静态代码块
static {
try {
// 加载驱动
Class.forName(DRIVERCLASSNAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 获取数据库连接
*/
public static Connection getConnection() {
Connection conn = null;
try{
conn= DriverManager.getConnection(URL, USERNAME, PASSWORD);
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}
/*
* 关闭数据库连接,释放资源
*/
public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
if(rs!=null){
try{
rs.close();
rs=null;
}catch(SQLException e){
e.printStackTrace();
}
}
if(ps!=null){
try{
ps.close();
ps=null;
}catch(SQLException e){
e.printStackTrace();
}
}
if(conn!=null){
try{
conn.close();
conn=null;
}catch(SQLException e){
e.printStackTrace();
}
}
}
/*
* 关闭数据库连接,释放资源
*/
public static void close2( PreparedStatement ps, Connection conn) {
if(ps!=null){
try{
ps.close();
ps=null;
}catch(SQLException e){
e.printStackTrace();
}
}
if(conn!=null){
try{
conn.close();
conn=null;
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
在类中具体使用:
public void AAA() {
try {
//连接数据库
conn = DataBaseConnectionUtil.getConnection();
String sql = "sql语句(一般这里留置占位符? 如insert into Test (A,B,C,D) values(?,?,?,?))";
ps = conn.prepareStatement(sql);
ps.setString(1, A);
ps.setString(2, B);
ps.setString(3, C);
ps.setInt(4, D);
// 执行sql语句
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接对象
DataBaseConnectionUtil.close2(ps, conn);
}
}