本文汇总了常见的Java JDBC关系型数据库连接字符串,包括MySQL,Postgres,SQL Server和DB2。
Database | URL (JDBC Connection String) | JDBC Driver |
---|---|---|
MySQL | jdbc:mysql://HOST/DATABASE | com.mysql.jdbc.Driver |
Postgresql | jdbc:postgresql://HOST/DATABASE | org.postgresql.Driver |
SQL Server | jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE | com.microsoft.jdbc.sqlserver.SQLServerDriver |
DB2 | jdbc:as400://HOST/DATABASE; | com.ibm.as400.access.AS400JDBCDriver |
Oracle | jdbc:oracle:thin:@localhost:1521:ORCL |
oracle.jdbc.driver.OracleDriver |
Here's a sample MySQL JDBC connection string and JDBC driver string, taken from a Java properties file:
如下是在java的properties文件中配置mysql的jdbc连接字符串的示例:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 user=system pwd=system
下面是一个java连接MYSQL 执行查询的代码示例:
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://HOST/DATABASE";
conn = DriverManager.getConnection(url, "username", "password");
doTests();
conn.close();
}
catch (ClassNotFoundException ex) {System.err.println(ex.getMessage());}
catch (IllegalAccessException ex) {System.err.println(ex.getMessage());}
catch (InstantiationException ex) {System.err.println(ex.getMessage());}
catch (SQLException ex) {System.err.println(ex.getMessage());}
如果你的mysql数据库监听的端口不是标准的3306,那么需要在连接字符串中指定端口号,如下使用了3336端口的示例:
db_url = jdbc:mysql://HOST:3336/DATABASE db_driver = com.mysql.jdbc.Driver db_username = USERNAME db_password = PASSWORD
要注意有可能会出现问题,具体什么问题我不记得了,我记得这个有时候要加的true&
下面是一个Postgresql jdbc连接字符串的properties文件的示例:
db_url = jdbc:postgresql://HOST/DATABASE db_driver = org.postgresql.Driver db_username = USERNAME db_password = PASSWORD
下面是java连接Postgresql的例子:
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://HOST/DATABASE";
Connection conn = DriverManager.getConnection(url,"username", "password");
如下java properties文件;
db_url = jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE db_driver = com.microsoft.jdbc.sqlserver.SQLServerDriver db_username = USERNAME db_password = PASSWORD
下面是jdbc连接db2数据库的示例,使用spring 配置文件配置。
id="as400DataSource" class="org.apache.commons.dbcp.BasicDataSource">
name="driverClassName" value="com.ibm.as400.access.AS400JDBCDriver" />
name="url" value="jdbc:as400://HOST/DATABASE;" />
name="username" value="USERNAME" />
name="password" value="PASSWORD" />
当然你也可以在java properties文件中配置:
db_url = jdbc:as400://HOST/DATABASE; db_driver = com.ibm.as400.access.AS400JDBCDriver db_username = USERNAME db_password = PASSWORD
oracle数据库 连接数据库
database.database=ORACLE
database.driverClassName = oracle.jdbc.driver.OracleDriver
database.password = system
database.show_sql = true
database.url = jdbc:oracle:thin:@localhost:1521:ORCL
database.username = system