各数据库连接数据库中db.properties中的写法

时间:2022-12-04 13:35:51

本文汇总了常见的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

MySQL JDBC 使用示例 (JDBC URL)

Here's a sample MySQL JDBC connection string and JDBC driver string, taken from a Java properties file:

如下是在java的properties文件中配置mysql的jdbc连接字符串的示例:

db_url      = jdbc:mysql://HOST/DATABASE
db_driver
= com.mysql.jdbc.Driver
db_username
= USERNAME
db_password
= PASSWORD

下面是一个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

Postgresql JDBC 连接字符串示例

下面是一个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");

SQL Server JDBC连接字符串示例

如下java properties文件;

db_url      = jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE
db_driver
= com.microsoft.jdbc.sqlserver.SQLServerDriver
db_username
= USERNAME
db_password
= PASSWORD

DB2 on an As/400 (iSeries) jdbc 连接示例

下面是jdbc连接db2数据库的示例,使用spring 配置文件配置。

<bean id="as400DataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.ibm.as400.access.AS400JDBCDriver" />
<property name="url" value="jdbc:as400://HOST/DATABASE;" />
<property name="username" value="USERNAME" />
<property name="password" value="PASSWORD" />
</bean>

当然你也可以在java properties文件中配置:

db_url      = jdbc:as400://HOST/DATABASE;
db_driver
= com.ibm.as400.access.AS400JDBCDriver
db_username
= USERNAME
db_password
= PASSWORD