本人用eclipse开发,jdbc驱动装好,请问还要怎么配置连接SQL SERVER?
答案:1 悬赏:30 手机版
解决时间 2021-04-06 06:07
- 提问者网友:刺鸟
- 2021-04-06 00:45
本人用eclipse开发,jdbc驱动装好,请问还要怎么配置连接SQL SERVER?
最佳答案
- 五星知识达人网友:一把行者刀
- 2021-04-06 01:15
写一个DB类进行连接。
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DB {
private Connection conn;
public Connection openConn() throws SQLException, ClassNotFoundException {
if (this.conn == null || this.conn.isClosed()) {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
this.conn = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;databaseName=数据库名",
"数据库用户名", "该用户的密码"); //localhost
}
return this.conn;
}
public void closeConn() {
try {
if ((this.conn != null) && (!this.conn.isClosed()))
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.conn = null;
}
}
}
然后在其它需要使用数据库的地方这样调用:
private DB db;
public DB getDb() {
return db;
}
public void setDb(DB db) {
this.db = db;
}
public int countGoodsByTypeId(Object typeId) throws SQLException,
ClassNotFoundException {
String sql = "SELECt COUNT(*) AS count FROM Goods WHERe GTID=?"; //SQL 语句
Connection conn = db.openConn();
PreparedStatement pstat = conn.prepareCall(sql);
pstat.setObject(1, typeId);
ResultSet rs = pstat.executeQuery();
rs.next();
return rs.getInt("count");
}
以上加粗的地方是需要修改的地方,其他地方根据情况进行修改。
如果不明白请追问。
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DB {
private Connection conn;
public Connection openConn() throws SQLException, ClassNotFoundException {
if (this.conn == null || this.conn.isClosed()) {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
this.conn = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;databaseName=数据库名",
"数据库用户名", "该用户的密码"); //localhost
}
return this.conn;
}
public void closeConn() {
try {
if ((this.conn != null) && (!this.conn.isClosed()))
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.conn = null;
}
}
}
然后在其它需要使用数据库的地方这样调用:
private DB db;
public DB getDb() {
return db;
}
public void setDb(DB db) {
this.db = db;
}
public int countGoodsByTypeId(Object typeId) throws SQLException,
ClassNotFoundException {
String sql = "SELECt COUNT(*) AS count FROM Goods WHERe GTID=?"; //SQL 语句
Connection conn = db.openConn();
PreparedStatement pstat = conn.prepareCall(sql);
pstat.setObject(1, typeId);
ResultSet rs = pstat.executeQuery();
rs.next();
return rs.getInt("count");
}
以上加粗的地方是需要修改的地方,其他地方根据情况进行修改。
如果不明白请追问。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯