Java 使用 JDBC 連接 SQL 資料庫
首先,確保你的 Java 環境中已經包含了 JDBC 驅動,這通常是一個 JAR 檔案,你可以將其加入到你的項目的 classpath 中。以下是一個典型的示例,使用 JDBC 來連接 SQL Server:
java
複製程式碼
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
public static void main(String[] args) {
// 這裡假設 connectionURL 包含了完整的連接資訊,如驅動類型、資料庫地址、資料庫名稱、用戶名和密碼
String connectionURL = "jdbc:sqlserver://localhost;databaseName=YourDatabase;user=YourUsername;password=YourPassword;";
try {
// 加載 SQL Server JDBC 驅動(確保驅動的 JAR 檔已被加到 classpath 中)
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// 建立連接
Connection conn = DriverManager.getConnection(connectionURL);
System.out.println("Successfully connected to the database.");
// 這裡可以添加更多操作資料庫的代碼...
// 關閉連接
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("An error occurred while connecting to the database.");
e.printStackTrace();
}
}
}
關鍵步驟解析:
加載驅動:使用 Class.forName() 方法來加載 JDBC 驅動。對於 SQL Server,驅動類是 com.microsoft.sqlserver.jdbc.SQLServerDriver。
建立連接:使用 DriverManager.getConnection() 方法和提供的連接字串來建立到資料庫的連接。
確保你更換 connectionURL 中的連接參數(如主機名、資料庫名、用戶名、密碼)以符合你的實際環境設定。此外,驅動名稱和 URL 格式可能會因所使用的 SQL 資料庫類型(如 MySQL, PostgreSQL 等)和版本而有所不同。