JDBC连接不同类型数据库
要使用JDBC连接不同类型的数据库,你需要确保你的项目中包含了对应数据库的JDBC驱动。以下是连接不同数据库的基本步骤和示例代码:
- 确保你的项目中包含了对应数据库的JDBC驱动。例如,对于MySQL,你需要添加
mysql-connector-java
的依赖。对于PostgreSQL,添加postgresql
的依赖。 - 在代码中,使用
DriverManager
获取数据库连接。
以下是连接不同数据库的示例代码:
连接MySQL数据库:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnectionExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the MySQL server successfully.");
connection.close();
} catch (SQLException e) {
System.out.println("Connection to MySQL failed: " + e.getMessage());
}
}
}
连接PostgreSQL数据库:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class PostgreSQLConnectionExample {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/mydb";
String user = "postgres";
String password = "password";
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the PostgreSQL server successfully.");
connection.close();
} catch (SQLException e) {
System.out.println("Connection to PostgreSQL failed: " + e.getMessage());
}
}
}
连接Oracle数据库:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class OracleConnectionExample {
public static void main(String[] args) {
String url = "jdbc:oracle:thin:@localhost:1521:mydb";
String user = "user";
String password = "password";
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the Oracle server successfully.");
connection.close();
} catch (SQLException e) {
System.out.println("Connection to Oracle fail
评论已关闭