JDBC回顾

来源:互联网 发布:生产线电子看板数据 编辑:程序博客网 时间:2024/06/05 14:52

事例代码

//connection,statement记得写在class的成员中。//statement.executeQuery()仅用于查询,return ResultSet;//statement.execute()如果是查询语句会返回true,如果是update或者insert就一定是返回false,所以如果要判断insert或者update是否成功可以使用executeUpdate(),返回的是执行成功的操作数量。public class MysqlTest {     static String url = "jdbc:mysql://localhost:3306/chatroom";     static String name = "root";     static String password ="";     static PreparedStatement statement;     static Connection connection;    public static void main(String[] args) {        try {            Class.forName("com.mysql.jdbc.Driver");             connection = DriverManager.getConnection(url,name,password);            if (!connection.isClosed())                System.out.println("连接成功");            connection.setAutoCommit(false);            String queryString = "INSERT INTO user_tb(username,password) VALUES('aaa','111')";            statement = connection.prepareStatement(queryString);            int caonima = statement.executeUpdate();            System.out.println(caonima);            connection.commit();            if (caonima>0)                System.out.println("插入成功");            System.out.println();        } catch (ClassNotFoundException | SQLException e) {            try {                connection.rollback();            } catch (SQLException e1) {                e1.printStackTrace();            }            e.printStackTrace();        }    }}
原创粉丝点击