java如何连接sql数据库
时间: 2023-06-24 21:05:17 浏览: 43
Java可以使用JDBC(Java Database Connectivity) API来连接SQL数据库。下面是一个连接MySQL数据库的示例代码:
```java
import java.sql.*;
public class ConnectToMySQL {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Create a connection to the database
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connection successful!");
// Do something with the connection...
} catch (SQLException e) {
System.out.println("Connection failed!");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver not found!");
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
System.out.println("Connection closed!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在这个例子中,我们使用了MySQL的jdbc驱动。如果你使用的是其他数据库,你需要使用相应的jdbc驱动。还需要替换url,user和password为你自己的数据库连接信息。