package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
private Connection conn = null;
public Test() {
super();
}
public void getConnection() {
try {
Class
.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
.newInstance();
String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=testDB";
String USER = "sa"; // 根据你自己设置的数据库连接用户进行设置
String PASSWORD = "123"; // 根据你自己设置的数据库连接密码进行设置
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (java.lang.ClassNotFoundException ce) {
System.out.println("Get Connection error:");
ce.printStackTrace();
} catch (java.sql.SQLException se) {
System.out.println("Get Connection error:");
se.printStackTrace();
} catch (Exception e) {
System.out.println("Get Connection error:");
e.printStackTrace();
}
}
public void testConnection() {
if (conn == null)
this.getConnection();
try {
String sql = "SELECT * FROM user";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.print(rs.getString("ID")+" ");
System.out.print(rs.getString("Name")+" ");
System.out.println(rs.getString("Email"));
}
rs.close();
stmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
}
}
}
public static void main(String[] args) {
Test bean = new Test();
bean.testConnection();
}
}
运行程序,没啥意外的话应该就OK了。连接代码与SQLServer2000的有所不同。这两句可以记下来备用~
Class.forName(”com.microsoft.sqlserver.jdbc.SQLServerDriver”).newInstance();
String URL = “jdbc:sqlserver://localhost:1433;DatabaseName=数据库名称”;