Java连接各种数据库操作(mysql、oracle、postgresql、gbase、mongo)
以下是使用Java连接不同数据库的示例代码。请确保你的项目中已经添加了对应数据库的JDBC驱动依赖。
MySQL:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnector {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/yourDatabase";
String user = "yourUsername";
String password = "yourPassword";
try {
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the MySQL server successfully.");
conn.close();
} catch (SQLException e) {
System.out.println("MySQL connection failed: " + e.getMessage());
}
}
}
Oracle:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class OracleConnector {
public static void main(String[] args) {
String url = "jdbc:oracle:thin:@localhost:1521:yourSID";
String user = "yourUsername";
String password = "yourPassword";
try {
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the Oracle server successfully.");
conn.close();
} catch (SQLException e) {
System.out.println("Oracle connection failed: " + e.getMessage());
}
}
}
PostgreSQL:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class PostgreSQLConnector {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/yourDatabase";
String user = "yourUsername";
String password = "yourPassword";
try {
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the PostgreSQL server successfully.");
conn.close();
} catch (SQLException e) {
System.out.println("PostgreSQL connection failed: " + e.getMessage());
}
}
}
GBase (南大通用):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class GBaseConnector {
public static void main(String[] args) {
String url = "jdbc:gbase://localhost:5258/yourDatabase";
String user = "yourUsername";
String password = "
评论已关闭