美文网首页
Java MySQL prepareStatement

Java MySQL prepareStatement

作者: Zihowe | 来源:发表于2017-07-27 14:36 被阅读156次

--
Example of insert

  • Get db connection to MySQL database
  • Create a sql statement, using the Java PreparedStatement syntax.
  • set the parameters values for the Java PreparedStatement object.
  • execute sql insert
  • close Java MySQL database connection.
  • Catch any SQL exceptions that may come up during the process.
    public void addStudent(Student theStudent) throws Exception {

        Connection myConn = null;
        PreparedStatement myStmt = null;
        
        try {
            // get db connection
            myConn = dataSource.getConnection();
            
            // create sql for insert
            String sql = "insert into student "
                       + "(first_name, last_name, email) "
                       + "values (?, ?, ?)";
            
            myStmt = myConn.prepareStatement(sql);
            
            // set the param values for the student
            myStmt.setString(1, theStudent.getFirstName());
            myStmt.setString(2, theStudent.getLastName());
            myStmt.setString(3, theStudent.getEmail());
            
            // execute sql insert
            myStmt.execute();
        }
        finally {
            // clean up JDBC objects
            close(myConn, myStmt, null);
        }
    }

Example of update

    public void updateStudent(Student theStudent) throws Exception {
        
        Connection myConn = null;
        PreparedStatement myStmt = null;

        try {
            // get db connection
            myConn = dataSource.getConnection();
            
            // create SQL update statement
            String sql = "update student "
                        + "set first_name=?, last_name=?, email=? "
                        + "where id=?"; 
            
            // prepare statement
            myStmt = myConn.prepareStatement(sql);
            
            // set params
            myStmt.setString(1, theStudent.getFirstName());
            myStmt.setString(2, theStudent.getLastName());
            myStmt.setString(3, theStudent.getEmail());
            myStmt.setInt(4, theStudent.getId());
            
            // execute SQL statement
            myStmt.execute();
        }
        finally {
            // clean up JDBC objects
            close(myConn, myStmt, null);
        }
    }

--
Reference:
https://alvinalexander.com/java/java-mysql-insert-example-preparedstatement
http://www.codejava.net/java-se/jdbc/jdbc-tutorial-sql-insert-select-update-and-delete-examples
https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html

相关文章

网友评论

      本文标题:Java MySQL prepareStatement

      本文链接:https://www.haomeiwen.com/subject/vwqnkxtx.html