dbconnection.java
来自「新闻发布系统」· Java 代码 · 共 134 行
JAVA
134 行
package DBOperation;
import java.sql.*;
public class DBConnection {
public Connection con; //连接
public Statement sta; //语句块
public PreparedStatement preSta; //预处理语句块
public ResultSet rs; //结果集
public String classStr;
public String conStr;
/**
* 指定所要操作的数据库名
*/
public DBConnection(String database) {
classStr = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; //加载驱动
conStr = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName="+database; //连接数据库
}
/**
*
* 带用户名与密码的连接
*/
public Connection getCon(String user,String pass) {
if(this.con == null) {
try {
Class.forName(classStr);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
try {
this.con = DriverManager.getConnection(conStr,user,pass);
this.sta = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
return this.con;
}
/**
*
* 默认连接
*/
public Connection getCon() {
if(this.con == null) {
try {
Class.forName(classStr);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
try {
this.con = DriverManager.getConnection(conStr,"sa","");
this.sta = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
return this.con;
}
/**
*
* 执行
*/
public boolean executeUpdate(String sql) {
if(this.con == null) {
this.getCon();
}
try {
this.sta.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/**
*
* 查询
*/
public ResultSet executeQuery(String sql) {
if(this.con == null) {
this.getCon();
}
try {
this.rs= this.sta.executeQuery(sql);
return this.rs;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* 关闭连接
*/
public void Close() {
try {
this.rs.close();
} catch(Exception ex) {
}
try {
this.sta.close();
} catch(Exception ex) {
}
try {
this.preSta.close();
} catch(Exception ex) {
}
try {
this.con.close();
} catch(Exception ex) {
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?