日期:2014-05-16  浏览次数:20526 次

JAVA数据库连接类写法
package com.dao;

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

public class GSYDao {
//定义对象
private PreparedStatement pstmt;
private Connection conn;
private ResultSet rs;

//加载驱动
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

//方法卸载构造方法内,开始就会调用。
public GSYDao(String sql){
try {
//获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost/test",
"root", "admin");
//存入pstmt对象,以供使用
pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
} catch (Exception e) {
e.printStackTrace();
}
}

public void executeUpdate(String sql) throws SQLException {
System.out.println(sql);
pstmt.executeUpdate(sql);
}

public ResultSet executeQuery(String sql) throws SQLException {
System.out.println(sql);
rs = pstmt.executeQuery(sql);
return rs;
}

public void close() {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
// TODO: handle exception
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (Exception e) {
// TODO: handle exception
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}

//main方法
public static void main(String[] args) {

}

}