Java-jdbc操作数据库

  如果需要访问数据库,首先要加载数据库驱动,数据库驱动只需在第一次访问数据库时加载一次。然后在每次访问数据库时创建一个Connection实例,获取数据连接,这样就可以执行操作数据库的SQL语句。最后在完成数据库操作时,释放与数据库的连接。

 

一、配置程序——让我们程序能找到数据库的驱动jar包
  1.把.jar文件复制到项目中去。
  2.在eclipse项目右击“构建路径”--“配置构建路径”--“库”--“添加外部jar”--找到数据库的驱动jar包--点击确定。会在左侧包资源管理器中出现“引用的库”,在里面就能找到我们刚才导入的jar包。这个包在这里使用的是Mysql的,这里分享一个下载地址https://pan.baidu.com/s/1bSEBIQ

二、做个数据库和表

 

三、写我们的程序来调用驱动包的类,对数据进行操作。
  //1.加载数据访问驱动
  Class.forName("com.mysql.jdbc.Driver");
  Mysql中的加载驱动位置是在引用的库中的com.mysql.jdbc下的Driver。


  //2.连接到数据"库"上去
  Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK","root","");

  这里的jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK是代表Mysql的Url地址。

  //3.构建执行SQL命令.....
  Statement state = conn.createStatement();
  state.executeUpdate("增删改的sql语句");
  state.executeQuery("查询的sql语句");

  conn.close();

JDBC的常用类和接口:

1.DriverManager类

  DriverManager类用来管理数据库中的所有驱动程序,是JDBC的管理层。作用于用户和驱动程序之间,跟踪可用的驱动程序,并在数据库的驱动程序之间建立连接。

方法 说明
getConnection(String url, String user, String password) 指定三个入口参数,一次是连接数据库的URL、用户名、密码,来获取与数据库的连接。

2.Connection接口

  Connection接口代表与特定的数据库的连接。要对数据表中的数据进行操作。首先要获取数据库连接。Connection实例就像在用用程序和数据库之间开辟的一条通道。

方法 说明
creatStatement() 创建Statement对象
prepareStatement() 创建预处理的prepareStatement对象
commit() 使所有上一次提交、回滚后进行的更改成为持久更改,并释放Connection对象当前持有的所有数据库锁
roolback() 取消在当前事务中进行的所有更改,并释放此Connection对象当前持有的所有数据库锁
close() 立即释放此Connection对象的数据库和JDBC资源,而不是等待它们被自动释放

3.Statement接口

  Statement接口用于创建向数据库中传递SQL语句的对象,该接口提供了一些方法可以实现对数据库的常用操作。

方法 说明
executeQuery() 执行给定的SQL语句,该语句返回单个ResultSet对象
executeUpdate() 执行给定的SQL语句, 该语句为insert into,update或delete语句
close()  释放Statement实例占用的数据库和JDBC资源

4.PreparedStatement接口

  PreparedStatement接口继承Statement,用于执行动态的SQL语句,通过PreparedStatement实例执行的SQL语句,将被预编译并保存到PreparedStatement实例中,从而可以反复地执行该SQL语句。

方法 说明
executeQuery() 在此PreparedStatement对象中执行SQL查询语句,返回结果为查询结果集ResultSet对象
executeUpdate() 在此PreparedStatement对象中执行SQL语句,该SQl语句必须是一个insert、update或者delete语句,或者是没有返回值的DDl语句
setObject(int pIndex,Object o) 将参数pIndex位置上设置为给定的Object型参数值
setString(int pIndex,String str)

将参数pIndex位置上设置为给定的String型参数值

5.ResultSet接口

  ResultSet接口类似于一个临时表,用来暂时存放数据库查询操作所获得的结果集。

方法 说明
getString() 以String形式获取ResultSet对象的当前行的指定列值。如列值是null,则返回null。
next() 将指针向下移一行
updateString() 用指定的String值更新列

  在这里,常用方法没有列举全,getInt(),getFloat(),getDate(),getBoolean(),getObject()都类似于getString()。同理,updateInt(),updateFloat(),updateObject(),updateNull,updateDate(),updateDouble()也是类似于updateString()。也同样适用与4.preparedStatement中的setString这一类。

举个增加数据的栗子:

public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.print("学号:");
        String xh =sc.nextLine();
        System.out.print("姓名:");
        String xm =sc.nextLine();
        System.out.print("学校: ");
        String xx =sc.nextLine();
        // 加载数据访问驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 连接到数据“库”上去
        java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK", "root", "");
        
        //构建SQL命令
        Statement state =conn.createStatement();
        String sql = "insert into xs values('"+xh+"','"+xm+"','"+xx+"')";
        state.executeUpdate(sql);
        //state.executeUpdate(sql); //增删改
        //state.executeQuery(sql); //查询
        
        conn.close();
        
        
    }

输入为:

学号:110
姓名:王十
学校: 一中

显示为:

 下面再是一个查询数据的例子:

   现有一个info表和nation表

现要把info表中的内容都输出出来,性别以男女区分,民族以nation表中的name显示,birthday用年月日显示:

public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK","root","");
        
        String sql ="select * from info";
        Statement state = conn.createStatement();
        ResultSet rs = state.executeQuery(sql);
        while(rs.next()){
            System.out.print(rs.getString(1)+"	");
            System.out.print(rs.getString(2)+"	");
            System.out.print(rs.getBoolean(3)?"男	":"女	");
            System.out.print(MinZu(rs.getString(4))+"	");
            System.out.print(RiQi(rs.getDate(5))+"
");
        }
        conn.close();
        
    }
    public static String MinZu(String mz) throws Exception{
        String mzmc="";
        Class.forName("com.mysql.jdbc.Driver");
        
        Connection conn =DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=gbk","root","");
        
        String sql = "select * from nation where code='"+mz+"'";
        Statement state = conn.createStatement();
        ResultSet rs = state.executeQuery(sql);
        while(rs.next()){
             mzmc=rs.getString(2);
        }
        
        conn.close();
        return mzmc;
    }
    public static String RiQi(Date date){
        SimpleDateFormat  simple =new SimpleDateFormat("yyyy年MM月dd日");
        return simple.format(date);
    }

输出结果为:

p001    胡军    男    满族    1985年08月09日
p002    周丹    女    汉族    1984年04月17日
p003    吴倩    女    苗族    1981年10月29日
p004    唐墨    男    汉族    1983年02月25日
原文地址:https://www.cnblogs.com/claricre/p/6246569.html