用jdbc-odbc桥来连接,不过这可是牺牲了速度来的。用jdbc-odbc桥的话,和连接access是一样的,先要设置一个数据源DNS,然后就用
import java.sql.*;
public class Dblei {
public Dblei() {
}
//直链接
//private Stringurl= "jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=UserInfo";
//private String user = "sa";
//private String password = "";
public Connection getConn()
{
try {
//Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); 直链接
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
try {
// return DriverManager.getConnection(url, user, password); 直连接
Connection conn= DriverManager.getConnection("jdbc:odbc:test");
return conn;
} catch (SQLException ex1) {
return null;
}
}
//关闭链接
public void closeAll(ResultSet rs,PreparedStatement pstmt,Connection conn)
{
if(rs!=null)
{
try {
rs.close();
} catch (SQLException ex1) {
System.out.println(ex1.getMessage());
}
}
if(pstmt!=null)
{
try {
pstmt.close();
} catch (SQLException ex2) {
System.out.println(ex2.getMessage());
}
}
if(conn!=null)
{
try {
conn.close();
} catch (SQLException ex3) {
System.out.println(ex3.getMessage());
}
}
}
//测试数据库是否连接?
public static void main(String args[]){
Dblei d=new Dblei();
if(d.getConn()!=null){
System.out.print("ok?");
}
}
}
阅读(542) | 评论(0) | 转发(0) |