Jdbc 连接数据库
1 连接字符串
SQLite
Class.forName("org.sqlite.JDBC"); Connection conn =DriverManager.getConnection("jdbc:sqlite:zieckey.db");
MySQL (http://www.mysql.com)
Class.forName( "org.gjt.mm.mysql.Driver" ); Connection conn = DriverManager.getConnection( "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", sUsr, sPwd );
PostgreSQL (http://www.de.postgresql.org)
Class.forName( "org.postgresql.Driver" ); Connection conn = DriverManager.getConnection( "jdbc:postgresql://MyDbComputerNameOrIP/myDatabaseName", sUsr, sPwd );
Oracle (http://www.oracle.com/ip/deploy/database/oracle9i/)
Class.forName( "oracle.jdbc.driver.OracleDriver" ); Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@MyDbComputerNameOrIP:1521:ORCL", sUsr, sPwd );
Microsoft SQLServer (http://jtds.sourceforge.net)
Class.forName( "net.sourceforge.jtds.jdbc.Driver" ); cn = DriverManager.getConnection( "jdbc:jtds:sqlserver://MyDbComputerNameOrIP:1433/master", sUsr, sPwd );
Microsoft SQLServer (http://www.microsoft.com)
Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" ); Connection conn = DriverManager.getConnection( "jdbc:microsoft:sqlserver://MyDbComputerNameOrIP:1433;databaseName=master",sUsr, sPwd );
2 释放资源的写法
public class DBUtil {
public static void close(Connection conn) {
close(conn, null, null);
}
public static void close(Connection conn, Statement stmt, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (Exception ignored) {}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception ignored) {}
}
if (conn != null) {
try {
conn.close();
} catch (Exception ignored) {}
}
}
}
3 连接 SQLite3 的示例
public void sqliteJDBCDemo() {
Connection conn = null;
try {
// 1. 驱动
Class.forName("org.sqlite.JDBC");
// 2. 打开连接
conn = DriverManager.getConnection("jdbc:sqlite:e:/data/student.sqlite3");
// 3. 操作
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("select name, weixin, score from student");
while (resultSet.next()) {
System.out.printf("Name: %s, Weixin: %s, Score: %f
",
resultSet.getString(1),
resultSet.getString(2),
resultSet.getFloat(3));
}
} catch (ClassNotFoundException e) {
System.out.println("1. 驱动加载失败");
} catch (SQLException e) {
System.out.println("2. 数据库异常");
} finally {
// 4. 释放资源
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}