JDBC连接Oracle、MySQL数据库

时间:2021-11-06 13:15:18

在连接数据库时,并不是所有的情况都适合使用Hibernate等框架,比如单独写一个报表服务,就需要使用简单高效的JDBC来连接:

1、数据库连接JDBC原理 : http://blog.csdn.net/jiangxinyu/article/details/1789019

2、Oracle---Class.forName

Class.forName("oracle.jdbc.OracleDriver"); 
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user = "scott"; 
String password = "tiger";  
Connection conn;
conn = DriverManager.getConnection(url,user, password);
3、Oracle---DriverManager

Driver driver = new oracle.jdbc.driver.OracleDriver();    
DriverManager.registerDriver(driver);
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user = "scott"; 
String password = "tiger";    
Connection conn = DriverManager.getConnection(url,user, password);

4、MySQL---Class.forName

Class.forName("com.mysql.jdbc.Driver"); 
String url = "jdbc:mysql://localhost:3309/hh";    
Properties info = new Properties();    
info.setProperty("user", "root"); 
info.setProperty("password", "root");    
Connection conn; 
conn = DriverManager.getConnection(url, info);
5、MySQL---DriverManager

Driver driver = new com.mysql.jdbc.Driver();    
DriverManager.registerDriver(driver);    
String url = "jdbc:mysql://localhost:3309/hh";    
Properties info = new Properties();    
info.setProperty("user", "root");    
info.setProperty("password", "root");    
Connection conn = DriverManager.getConnection(url, info);    

6、MySQL---Driver

Driver driver = new com.mysql.jdbc.Driver();    
String url = "jdbc:mysql://localhost:3309/hh";    
Properties info = new Properties();    
info.setProperty("user", "root");    
info.setProperty("password", "root");    
Connection conn = driver.connect(url, info); 

7、使用

Connection con = null;// 创建一个数据库连接
PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
ResultSet result = null;// 创建一个结果集对象
String sql = "select * from student where name=?";// 预编译语句,“?”代表参数
pre = con.prepareStatement(sql);// 实例化预编译语句
pre.setString(1, "刘显安");// 设置参数,前面的1表示参数的索引,而不是表中列名的索引
result = pre.executeQuery();// 执行查询,注意括号中不需要再加参数
while (result.next())
// 当结果集不为空时
System.out.println("学号:" + result.getInt("id") + "姓名:"
+ result.getString("name"));

8、关闭连接

finally {  
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

9、完整示例代码: http://www.cnblogs.com/liuxianan/archive/2012/08/05/2624300.html

10、MySQL的jdbc连接数据库参考:https://wenku.baidu.com/view/139ee221915f804d2b16c163.html

11、idea环境下详细实现过程:http://blog.csdn.net/haishu_zheng/article/details/50255665