1, 首先在配置文件(system.properties)中配置上如下内容:
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=mp
username=sa
password=mengya
2, 写了个SQLDB的工具类
public class SQLDBConnection {
private InputStream inputstr;
private Properties pro;
private static SQLDBConnection sqldb=null;
//私有构造方法
private SQLDBConnection(){
inputstr=this.getClass().getResourceAsStream("/system.properties");
pro=new Properties();
try {
pro.load(inputstr);
} catch (IOException e) {
e.printStackTrace();
}
try {
Class.forName(pro.getProperty("driver"));//注册驱动,只注册一次
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//单例模式
public static SQLDBConnection getSQLDBConnection(){
if(sqldb==null){
synchronized (SQLDBConnection.class) {
if(sqldb==null){
sqldb=new SQLDBConnection();
}
}
}
return sqldb;
}
//得到与数据库的连接
public Connection GetConnection(){
Connection conn=null;
try {
conn=DriverManager.getConnection(pro.getProperty("url"), pro.getProperty("username"), pro.getProperty("password"));
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
} 3, 写好Studao的接口
//释放资源
public static void free(ResultSet rs,Statement sta,Connection conn){
try{
if(rs!=null){
rs.close();
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(sta!=null){
sta.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
public interface Studaointer {
public void addStu(Stu stu);
public void delStu(int sid);
public void updStu(Stu stu);
public Stu getOneStu(int sid);
public List getAllStu();
}
4, 写好自己定义的RuntimeException
public class MySQLException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
5, 写好Studao的实现类
public class StuDAOImple implements Studaointer {
private Connection conn;
private PreparedStatement pre;
private ResultSet rs;
public void addStu(Stu stu) {
String sql="insert into stu values(?,?,?)";
conn=SQLDBConnection.getSQLDBConnection().GetConnection();
try {
pre=conn.prepareStatement(sql);
pre.setString(1, stu.getSname());
pre.setString(2, stu.getSsex());
pre.setDate(3, new java.sql.Date(stu.getSbrith().getTime()));
pre.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new MySQLException();//异常向上抛
}finally{
SQLDBConnection.free(rs, pre, conn);
}
}
public void delStu(int sid) {
String sql="delete stu where s_id=?";
conn=SQLDBConnection.getSQLDBConnection().GetConnection();
try {
pre=conn.prepareStatement(sql);
pre.setInt(1, sid);
pre.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new MySQLException();
}finally{
SQLDBConnection.free(rs, pre, conn);