当前位置:Gxlcms > 数据库问题 > JDBC的简单操作

JDBC的简单操作

时间:2021-07-01 10:21:17 帮助过:19人阅读

代码如下:
mysql> create database person;
Query OK, 1 row affected (0.00 sec)

 

mysql> use person;
Database changed
mysql> create table student(
    -> id int,
    -> name varchar(20),
    -> birth year
    -> ) default charset=utf8;
Query OK, 0 rows affected (0.10 sec)


然后往里面插入几条数据

复制代码代码如下:
mysql> insert into student values
    -> (1,‘张三‘,1990),
    -> (2,‘李四‘,1991),
    -> (3,‘王五‘,1992);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0


这样一张简单的表就建好了

复制代码代码如下:
mysql> select * from student;
+------+--------+-------+
| id   | name   | birth |
+------+--------+-------+
|    1 | 张三   |  1990 |
|    2 | 李四   |  1991 |
|    3 | 王五   |  1992 |
+------+--------+-------+
 rows in set (0.00 sec)


接下来,去mysql官网下载数据库连接器这个包

 

其中这个包里面含有一份文档,里面列举了基本的使用方法,可以参考

我们的操作也是按照这份文档中的内容进行,然后最主要的地方就是导入这个jar包

 

为了操作方便,这里使用eclipse来导入

右键项目-->构件路径-->添加外部归档,添加好了之后如下所示

 

现在我们正式开始使用java来操作mysql数据库

JDBC操作实例1:最简单的查询操作

复制代码代码如下:
import java.sql.*;

 

public class Demo {
    //为了代码紧凑性,暂时抛出所有异常
    public static void main(String[] args) throws Exception {
        //注册数据库驱动
        Class.forName("com.mysql.jdbc.Driver");
        //建立数据库连接
        //参数一:jdbc:mysql//地址:端口/数据库,参数二:用户名,参数三:密码
        Connection conn = DriverManager.getConnection
                ("jdbc:mysql://localhost:3306/person","root","admin");
        //创建SQL语句
        Statement st = conn.createStatement();
        //执行语句,返回结果
        ResultSet rt = st.executeQuery("show tables");
        //循环取出结果
        while(rt.next()) {
            //获取字段
            System.out.println(rt.getString("Tables_in_person"));
        }
        //关闭资源,最先打开的最后关
        rt.close();
        st.close();
        conn.close();
    }
}


运行结果:student

 

如此便可执行show tables语句查询出当前数据库含有多少张表

其中rt.getString()方法是获取字段,这点需要注意

关闭资源的方式也与以往相反

不过,上面的操作方式灵活性不大,并且不严谨


实例2:优化的查询操作

复制代码代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

 

public class Demo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";
        String sql = "select * from student";

        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //执行查询语句,另外也可以用execute(),代表执行任何SQL语句
            rs = st.executeQuery(sql);
            while(rs.next()) {
                System.out.println(rs.getObject(1) + "  " + 
                        rs.getObject(2) + "  " + rs.getInt("birth"));
            }
        //分别捕获异常
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                //判断资源是否存在
                if(rs != null) {
                    rs.close();
                    //显示的设置为空,提示gc回收
                    rs = null;
                }
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }    
        }
    }
}


运行结果:

 

 

这里把异常给分别捕获了,并且相关的字符串全部用变量定义

需要注意下循环取出数据里面的getInt()方法,此处必须知道类型和字段才能取出

如果不知道可以使用getObject(1)取出第一列,getObject(2)取出第二列,以此类推

实例3:自定义变量插入到数据库

复制代码代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

 

public class Demo {
    public static void main(String[] args) {
        //参数检查
        if (args.length != 3) {
            System.out.println("参数形式不对");
            System.exit(0);
        }
        String id = args[0];
        String name = args[1];
        String birth = args[2];
        String sql = "insert into student values(" + id + ",‘" + name + 
                "‘," + "‘" + birth + "‘)";
        System.out.println(sql);

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //注意,此处是excuteUpdate()方法执行
            st.executeUpdate(sql);        
        //分别捕获异常
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }    
        }
    }
}


运行结果:

 

 

这里运行需要设置自变量,窗口中右键-->运行方式-->运行配置

然后在自变量里面写4 susan 1993,我没有写中文,因为产生乱码,目前还不清楚原因

需要注意的是,执行插入的SQL语句比较难写,最好是打印出SQL语句用以检查

实例4:PreparedStatement应用

从上面的Demo可以看到,插入数据的时候,SQL操作相当不便

这里可以使用PreparedStatement对象来简化SQL语句的建立

复制代码代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

 

public class Demo {

    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("参数形式不对");
            System.exit(0);
        }
        String id = args[0];
        String name = args[1];
        String birth = args[2];

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        //声明PreparedStatement对象的引用
        PreparedStatement pst = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            //使用?代替变量
            pst = conn.prepareStatement("insert into student values (?,?,?)");
            //给指定参数的位置设定变量
            pst.setString(1, id);
            pst.setString(2, name);
            pst.setString(3, birth);
            pst.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(pst != null) {
                    pst.close();
                    pst = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }    
        }
    }
}


运行结果:

 

 

实例5:Batch批处理

复制代码代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

 

public class Demo {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //添加批处理
            st.addBatch("insert into student values(6,‘Jerry‘,‘1995‘)");
            st.addBatch("insert into student values(7,‘Greg‘,‘1996‘)");
            st.addBatch("insert into student values(8,‘Ryan‘,‘1997‘)");
            //执行批处理
            st.executeBatch();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }    
        }
    }
}


运行结果:

 

 

批处理比较简单,只需先建立Statement对象,然后逐个添加批处理即可

最后使用executeBatch()方法执行批处理

此外,PreparedStatement对象也可以使用批处理

复制代码代码如下:
PreparedStatement ps = conn.prepareStatement("insert into student values(?,?,?)");
ps.setInt(1,8);
ps.setString(2,"GG");
ps.setString(3,"1996");
ps.addBatch();
ps.executeBatch();


实例6:Transaction事务处理

 

事务处理是要求sql以单元的形式更新数据库,要求其确保一致性

如银行的转账业务,一方转出后,另一方则增加

如果出现异常,那么所有的操作则会回滚

复制代码代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

 

public class Demo {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            //取消自动提交
            conn.setAutoCommit(false);
            st = conn.createStatement();
            st.addBatch("insert into student values(6,‘Jerry‘,‘1995‘)");
            st.addBatch("insert into student values(7,‘Greg‘,‘1996‘)");
            st.addBatch("insert into student values(8,‘Ryan‘,‘1997‘)");
            st.executeBatch();
            //提交后设置自动提交
            conn.commit();
            conn.setAutoCommit(true);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();

            if(conn != null) {
                try {
                    //出现异常则回滚操作,然后设置自动提交
                    conn.rollback();
                    conn.setAutoCommit(true);
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }    
        }
    }
}

JDBC的简单操作

标签:简化   连接   next   建立数据库   lin   变量定义   执行sql   查询   lex   

人气教程排行