java 连接数据库
一共分三步:
一:加载驱动程序
二:获取数据库连接
三:建立statement 对象(将数据放到数据库中)
(四:执行sql语句)
共涉及三个对象:
1.Connection 对象(连接) conn
2.Statement对象(传输数据)sta
3.ResultSet对象(执行结果) rt
代码解读:
首先声明三个对象:
Connection conn = null; Statement sta = null; ResultSet rs = null;
一:加载驱动程序(用到了反射的技术,通过类名反向将类加载到环境中)
参数名:驱动名
Class.forName("oracle.jdbc.driver.OracleDriver");
二:获取数据库连接
在类中定义这三个变量,也可以直接把变量内容放到语句中;
private static String URL ="jdbc:oracle:thin:@localhost:1521:orcl"; private static String NAME = "scott"; private static String PASSWORD = "123456";
conn = DriverManager.getConnection(URL, NAME, PASSWORD);
三:建立statement 对象(将数据放到数据库中)
sta = conn.createStatement();
(四:执行sql语句)
rs = sta.executeQuery("select * from t_supplier"); while(rs.next()){ System.out.print(rs.getString("f_sid")); System.out.println(rs.getString("f_sname")); }
***在第一条语句后面一定要加while语句,否则编译会通过,但是运行会报错
rs.getString()参数为String类型的属性名
(五)关闭连接
try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { sta.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { rt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }
程序:
package com.imooc.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class test { private static String URL = "jdbc:oracle:thin:@localhost:1521:orcl"; private static String USER = "scott"; private static String PASSWORD = "123456"; public static void main(String[] args) { /* 三个变量 */ Connection conn = null; Statement sta = null; ResultSet rt = null; /* 三个过程 */ // 加载驱动程序 try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 获得数据库链接 try { conn = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 建立statement对象 try { sta = conn.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 执行语句 try { rt = sta.executeQuery("select * from t_supplier"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { while (rt.next()) {
System.out.println(rt.getString("f_sid"));
System.out.println(rt.getString("F_Sname"));
} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { sta.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { rt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }