java链接数据库SQL Server代码
时间: 2023-08-10 16:03:48 浏览: 91
java连接sql server 数据库代码
以下是Java连接SQL Server数据库的代码示例:
```
import java.sql.*;
public class SQLServerExample {
public static void main(String[] args) {
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=your_database_name;user=your_username;password=your_password;";
try {
// Establish a connection
Connection connection = DriverManager.getConnection(connectionUrl);
// Execute a query
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM your_table_name");
// Process the results
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// Close the connection
connection.close();
}
catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
}
}
}
```
在上面的代码中,你需要将 `your_database_name`,`your_username` 和 `your_password` 替换为你的数据库名称、用户名和密码。你还需要将 `your_table_name` 替换为你要查询的表的名称。
阅读全文