JDBC回顧

事例代碼

//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();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章