java程序与SQLServer2008数据库加载驱动并连接源代码

时间:2021-10-14 07:14:57

  import java.sql.*;


public class SQLServer_Connection {
public static void main(String[] args) {
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://localhost:1433;DatabaseName=MyDatabase";
String userName = "sa";
String userPwd = "177033";
Statement stmt = null;
ResultSet rs = null;
// 加载与SQLserver数据库连接的驱动
try {
Class.forName(driverName);
System.out.println("加载驱动成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
try {
// 与数据库连接
Connection conn = DriverManager.getConnection(dbURL, userName, userPwd);
System.out.println("连接数据库成功!");

String SQL = "SELECT * FROM BasicTable";
    stmt = conn.createStatement();
    rs = stmt.executeQuery(SQL);

    

//输出指定数据库表中的相关信息

    // Iterate through the data in the result set and display it.
    while (rs.next()) {
    System.out.println(rs.getString(1) + " " + rs.getString(2) + "\t" + rs.getString(3));
    }
} catch (Exception e) {
e.printStackTrace();
System.out.print("SQL Server连接失败!");
}
}
 }