package cn.hr.csdn.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DBManager {
/**
* @param args
*/
static String driver;
static String url;
static String password;
static String user;
static{
InputStream in=DBManager.class.getClassLoader().getResourceAsStream("db.properties");
Properties pro=new Properties();
try {
pro.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver = pro.getProperty("driver");
url = pro.getProperty("url");
password = pro.getProperty("password");
user = pro.getProperty("user");
}
public static Connection getConnection(){
Connection con=null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con=DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static void closeDB(Connection con,Statement st,ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(st!=null)
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
getConnection();
}
}
主方法
package cn.hr.csdn.demo;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import cn.hr.csdn.util.DBManager;
public class JDBCDemo3 {
/**
* @param args
*/
public void insert(){
Connection con=DBManager.getConnection();
Statement st=null;
try {
st=con.createStatement();
String sql="insert into users values('009','zzz','666',60)";
int i=st.executeUpdate(sql);
if(i>0){
System.out.println("插入成功");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBManager.closeDB(con, st, null);
}
}
public void update(){
}
public void delete(){
}
public static void main(String[] args) {
JDBCDemo3 d=new JDBCDemo3();
d.insert();
}
}