1:加载jdbc驱动
Class.forName("oracle.jdbc.OracleDriver");
2:定义数据库路径,用户名,密码
String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
String username = "";
String pwd = "";
3:建立链接
Connection conn = DriverManager.getConnection(url, username, pwd);
4:创建statement对象
Statement sm = conn.createStatement();
5:执行sql返回结果集
ResultSet rs = sm.executeQuery("select * from tbname");
if(rs.next()){
System.out.println("读取数据成功");
}
6:关闭结果集,statement对象和链接
rs.close();
sm.close();
conn.close();
以下是各种常用数据的链接信息
// HypersonicSQL
String hsqldbDriver = "org.hsqldb.jdbcDriver";
String hsqldbURL = "jdbc:hsqldb:hsql://localhost";
String hsqlUser = "sa";
String hsqlpwd = "";
//H2 (www.h2database.com)
String h2dbDriver = "org.h2.Driver";
String h2dbURL = "jdbc:h2:tcp://dbserv:8084/sample";
String h2User = "sa";
String h2pwd = "";
//MySQL
String mysqldbDriver = "com.mysql.jdbc.Driver";
String mysqldbURL = "jdbc:mysql://test";
String mysqlUser = "gavin";
String mysqlpwd = "";
//Oracle
String orcldbDriver = "oracle.jdbc.driver.OracleDriver";
String orcldbURL = "jdbc:oracle:thin:@localhost:1521:orcl";
String orclUser = "ora";
String orclpwd = "ora";
//PostgreSQL
String psqlDriver = "org.postgresql.Driver";
String psqldbURL = "jdbc:postgresql:template1";
String psqlUser = "pg";
String psqlpwd = "";
//DB2
String db2Driver = "com.ibm.db2.jcc.DB2Driver";
String db2URL = "jdbc:db2://localhost:50000/somename";
String db2User = "db2";
String db2pwd = "db2";
//MS SQL Server2005
String sqlserverDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String sqlserverURL = "jdbc:sqlserver://localhost:1433;databaseName=selectcourse";
String sqlserverUser = "";
String sqlserverpwd = "";