1个回答
展开全部
需要下载SQL Server驱动,直接在官网下载
package SQLServerConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLServerConnection {
// public static Connection con;
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// System.out.println("加载驱动成功");
con = DriverManager
.getConnection(
"jdbc:sqlserver://localhost:1433;DatabaseName=Student_Info_20123116",
"sa","zhang123456");
// System.out.println("连接成功");
String sql ="SELECT * FROM Student_20123116";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(2) +"t"+ rs.getString(3)
+"t"+ rs.getString(4) +"t"+ rs.getString(5));
}
} catch (Exception ex) {
// System.out.println("连接失败");
ex.printStackTrace();
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (stmt != null)
try {
stmt.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
}
}
并且把jdbc中的jdbc4.jar包复制到项目的bin目录下,并解压,如果是SQL Server2005就复制jdbc.jar包,然后解压到该项目下的bin目录下
package SQLServerConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLServerConnection {
// public static Connection con;
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// System.out.println("加载驱动成功");
con = DriverManager
.getConnection(
"jdbc:sqlserver://localhost:1433;DatabaseName=Student_Info_20123116",
"sa","zhang123456");
// System.out.println("连接成功");
String sql ="SELECT * FROM Student_20123116";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(2) +"t"+ rs.getString(3)
+"t"+ rs.getString(4) +"t"+ rs.getString(5));
}
} catch (Exception ex) {
// System.out.println("连接失败");
ex.printStackTrace();
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (stmt != null)
try {
stmt.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
}
}
并且把jdbc中的jdbc4.jar包复制到项目的bin目录下,并解压,如果是SQL Server2005就复制jdbc.jar包,然后解压到该项目下的bin目录下
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询