import java.sql.*;
public class Connect
{
static Connection con;
static Statement stmt;
public static void doConnect() throws SQLException
{
String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// SQL数据库引擎
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=JavaPattern";// 数据源
try {
Class.forName(JDriver);// 加载数据库引擎,返回给定字符串名的类
} catch (ClassNotFoundException e) {
System.out.println("加载数据库引擎失败");
System.exit(0);
}
System.out.println("数据库驱动成功");
try {
String user = "sa";
String password = "huxiang";
con = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
System.out.println("连接数据库成功");
stmt = con.createStatement();
}
catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接错误");
System.exit(0);
}
ResultSet rs = stmt.executeQuery("SELECT * FROM Student ");
while (rs.next()) {
System.out.println(rs.getString("id") + "\t"
+ rs.getString("password"));
}
System.out.println("读取完毕");
stmt.close();
con.close();
System.out.println("数据库关闭成功!");
}
public static void main(String[] args) {
try {
doConnect();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
使用Java查询Sql Server数据库
最新推荐文章于 2024-05-28 15:17:40 发布