1 package hanqi;
2
3 import java.sql.*;
4
5 public class JdbcTest
6 {
7
8 public static void main(String[] args)
9 {
10 // 测试JDBC
11 // 1.加载注册驱动
12 Connection conn = null;
13 try
14 {
15 // 每一种数据库都提供不同的驱动名
16 Class.forName("oracle.jdbc.driver.OracleDriver");// 加载驱动类
17
18 // 获取连接地址
19 String strUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";//由协议和地址名称组成
20 // 2.连接数据库;用户名,密码,URL数据库地址,得到连接Connection
21 conn = DriverManager.getConnection(strUrl, "text", "123456");
22 System.out.println("连接成功");
23 // 3.操作数据库,增删改查
24 //执行sql语句完成相应的功能
25 Statement st=conn.createStatement();
26 //DML执行增删该语句
27 int i=st.executeUpdate("update student set sname='小四' where sno='101'");
28 if(i>0)
29 {
30 System.out.println("操作数据库成功,影响了"+i+"数据");
31 }
32 else
33 {
34 System.out.println("操作数据库失败");
35 }
36
37 //DQL查询语句
38 //结果集
39 ResultSet rs=st.executeQuery("select * from student");
40
41 //遍历结果集
42 while(rs.next())
43 {
44 //字段序号
45 String sno=rs.getString(1);
46 //字段名称
47 String sname=rs.getString("sname");
48
49 Date dt=rs.getDate(4);
50 System.out.println("学号="+sno+"姓名="+sname+"生日"+dt.toString());
51 }
52 // rs.first();//到首行
53 // rs.last();//到最后一行
54 // rs.previous();//向后移动
55 rs.close();
56 st.close();
57 //支持占位符和在数据库中预编译
58 PreparedStatement ps=conn.prepareStatement("update student set sname='小四' where sno=?");
59 //?—占位符,需要替换成真正的值
60 ps.setString(1, "104");
61 ps.executeUpdate();
62 System.out.println("执行PreparedStatement成功");
63 ps.close();
64
65 }
66
67
68
69 catch (Exception e)
70 {
71 e.printStackTrace();
72 System.out.println("连接失败");
73 }
74 finally {
75 try
76 {
77 // 4.关闭连接
78 conn.close();
79 }
80 catch (SQLException e)
81 {
82
83 e.printStackTrace();
84 }
85 }
86
87 }
88
89 }