/*
* 连接数据库
*/
private static void dbconn(){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
String conURL="jdbc:sqlserver://localhost:1433;DatabaseName=YourDatabaseName";//数据源注意IP地址和端口号,数据库名字!!
try{
con = DriverManager.getConnection(conURL,userName ,password);//填写你数据库的用户名和密码,默认为sa 12345678
st = con.createStatement();
}catch(SQLException e){
e.printStackTrace();
}
}
上面是连接数据库的操作函数,注意数据库的名字。
/*
* 关闭数据库
*/
private static void dbclose(){
try{
st.close();
con.close();
}catch(SQLException e){
e.printStackTrace();
}
st=null;
con=null;
}
上面是关闭数据库连接的操作函数
/*
* 查询数据库
*/
public static ResultSet getDateSet(String sql){
dbconn();
try{
rs = st.executeQuery(sql);
}catch(SQLException e){
e.printStackTrace();
}
//dbclose();此条语句应注释
return rs;
}
查询数据库操作
/*
* 插入,删除,更新数据库
*/
public static int Execute(String sql){
int i=0;
dbconn();
try{
i=st.executeUpdate(sql);
}catch(SQLException e){
e.printStackTrace();
}
dbclose();
return i;//返回执行的行数
}
相关代码和jdbc驱动可以到这里
下载