jdbc连接oracle数据库
jdbc是sun公司提出在Java中访问不同数据库而定义的标准
步骤:
一. 导入jdbc驱动(不同的数据库驱动不同,一般是*.jar文件)
二. 数据库连接
- 注册驱动
Class.forName("Oracle.jdbc.driver.OracleDriver");
- 获取连接
Connection con = DriverManager.getConnection("jdbc:oracle:thin:localhost:1521:orcl","username","pwd");
- 与数据库通信
Statement stm = con.createStatement();
- 处理结果
ResultSet rs = stm.executeQuery(sql);//同样如果增删改则为executeUpdate
- 关闭连接
rs.closs(); stm.close(); con.close();
源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement;
public class Test2 { public static void main(String[] args) { String driverStr = "oracle.jdbc.driver.OracleDriver"; String conrul = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; String user = "******"; String pwd = "******"; Connection con = null; Statement stm = null; ResultSet rs = null; try { Class.forName(driverStr); con = DriverManager.getConnection(conrul, user, pwd); stm = con.createStatement(); String sql = "select * from student"; rs = stm.executeQuery(sql); System.out.println("名字\tid\t性别\t地址"); while (rs.next()) { System.out.println(rs.getString("name") + "\t" + rs.getString("id") + "\t" + rs.getString("age")+ "\t" + rs.getString("address")); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } else if (stm != null) { stm.close(); } else if (con != null) { con.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
|