package com.hanqi.test;

import java.sql.*;

public class jdbcTest {

    public static void main(String[] args) {

        // 测试JDBC

        Connection conn = null;

        try {

            // 1.加载驱动和注册
            // 每一种数据库提供不同的驱动名
            Class.forName("oracle.jdbc.driver.OracleDriver");// 加载

            // 2.连接数据库 :用户名,密码,URL数据库地址
            // url-
            String strUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";

            // 得到连接
            conn = DriverManager.getConnection(strUrl, "test1", "1234");

            System.out.println("连接数据库成功");

            // 3.操作数据库,增删改查
            // 执行sql语句完成响应的功能

            Statement st = conn.createStatement();

            // 执行增删改语句
            int i = st.executeUpdate("update T_students set sname = '小四' where sno = '101'");
            if (i > 0) 
            {
                System.out.println("操作数据库成功,影响了" + i + "数据");
            } 
            else 
            {
                System.out.println("未修改任何数据 ");
            }

            //DQL 查询
            //结果集
            ResultSet rs = st.executeQuery("select * from  T_students");
            
            //遍历结果集
            while(rs.next())
            {
                //字段序号
                String sno = rs.getString(1);
                //字段名称
                String sname = rs.getString("sname");
                
                Date dt = rs.getDate(4);
            
                System.out.println("学号= " + sno + "  学生姓名 = " + sname + "  生日= " + dt.toString());
            }
            
            //rs.first();//跳到首行
            
            //rs.last();//跳到尾行
            
            //rs.previous();//向上移动
            
            //rs.is
            
            rs.close();
            
            
            st.close();

            // 4.关闭连接
            
            //支持占位符和在数据库中预编译
            PreparedStatement ps = conn.prepareStatement("update T_students set sname = '小大123' where sno = ?");
            
            // ? - 占位符,需要替换成真正的值
            ps.setString(1, "108");
            
            ps.executeUpdate();
            
            System.out.println("执行prepareStatement成功!");
            
            ps.close();
            
        }

        catch (Exception e)

        {

            e.printStackTrace();
            System.out.println("连接数据库失败");
        } 
        finally 
        {
            if (conn != null)
            {
                try
                {
                    conn.close();
                } 
                catch (SQLException e) 
                {
                
                    e.printStackTrace();
                }
            }
        }
    }

}

 

 

 

posted on 2016-06-20 15:32  周帝  阅读(363)  评论(0编辑  收藏  举报