主题:JAVA连接数据库问题
package com.accp;
import java.sql.*;
public class DbManager {
// .\sqlexpress
private Connection con;
private Statement stm;
public DbManager() {
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //加载驱动
con = DriverManager.getConnection(
"jdbc:microsoft:sqlserver://localhost:1433;DataName=DbManager",
"sa", ""); //连接数据库
} catch (SQLException ex) {
System.out.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
public int exeSql(String sql) {
try {
stm = con.createStatement();
return stm.executeUpdate(sql);
} catch (SQLException ex) {
return 0;
}
}
public ResultSet query(String sql) {
try {
stm = con.createStatement();
return stm.executeQuery(sql);
} catch (SQLException ex) {
return null;
}
}
public void closeDB() {
try {
stm.close();
con.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
DbManager db = new DbManager();
ResultSet rs = db.query("select * from admin");
try {
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2) +
"\t" + rs.getString(3) + "\t" +
rs.getString(4));
}
} catch (SQLException ex) {
System.out.println(ex.getMessage()+"显示错误!");
}
}
}
还有就是 现在连接是sql2005
我用以前连 2000 的 DbManager 可以连 2005
可是我从新写一个也不行我把连2000的哪个例字(重新复制)也连不上
import java.sql.*;
public class DbManager {
// .\sqlexpress
private Connection con;
private Statement stm;
public DbManager() {
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //加载驱动
con = DriverManager.getConnection(
"jdbc:microsoft:sqlserver://localhost:1433;DataName=DbManager",
"sa", ""); //连接数据库
} catch (SQLException ex) {
System.out.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
public int exeSql(String sql) {
try {
stm = con.createStatement();
return stm.executeUpdate(sql);
} catch (SQLException ex) {
return 0;
}
}
public ResultSet query(String sql) {
try {
stm = con.createStatement();
return stm.executeQuery(sql);
} catch (SQLException ex) {
return null;
}
}
public void closeDB() {
try {
stm.close();
con.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
DbManager db = new DbManager();
ResultSet rs = db.query("select * from admin");
try {
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2) +
"\t" + rs.getString(3) + "\t" +
rs.getString(4));
}
} catch (SQLException ex) {
System.out.println(ex.getMessage()+"显示错误!");
}
}
}
还有就是 现在连接是sql2005
我用以前连 2000 的 DbManager 可以连 2005
可是我从新写一个也不行我把连2000的哪个例字(重新复制)也连不上