1. 程式人生 > >java程式與SQLServer2008資料庫載入驅動並連線原始碼

java程式與SQLServer2008資料庫載入驅動並連線原始碼

   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連線失敗!");
}
}
 }