请写出Java连接SQL Server数据库的代码
时间: 2023-12-08 20:04:11 浏览: 170
好的,以下是Java连接SQL Server数据库的代码:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
// JDBC driver name and database URL
String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String DB_URL = "jdbc:sqlserver://localhost:1433;databaseName=your_database_name";
// Database credentials
String USER = "your_username";
String PASS = "your_password";
Connection conn = null;
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Do something with the connection here
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
```
这段代码使用了JDBC驱动程序连接数据库。需要确保您已经下载并安装了适用于SQL Server的JDBC驱动程序,以便在代码中引用正确的驱动程序类名称。
阅读全文