PreparedStatement represents a precompiled SQL statement. It is alternative to Statement
At first Create named student a table in MySQL database as
CREATE TABLE `student` (
`rollno` int(11) NOT NULL,
`name` varchar(50) default NULL,
`course` varchar(20) default NULL,
PRIMARY KEY (`rollno`)
)
following is an example of JDBC PreparedStatement with MySql database.
MySqlPreparedStatement.java
package roseindia.net;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySqlPreparedStatement {
public static void main(String[] args) throws SQLException {
System.out.println("MySQL Insert PreparedStatement Example.");
Connection conn = null;
PreparedStatement ptmt = null;
// 3306 is the default port number of MySQL
// 192.168.10.13 is host address of the MySQL database
String url = "jdbc:mysql://localhost:3306/";
String dbName = "student";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
// Load the driver
Class.forName(driver);
// Get a connection
conn = DriverManager
.getConnection(url + dbName, userName, password);
System.out.println("Connected to the database");
// Create a query String
String query = "INSERT INTO STUDENT(rollno,name,course) VALUES(?,?,?)";
// Create a PreparedStatement
ptmt = conn.prepareStatement(query);
ptmt.setInt(1, 8);
ptmt.setString(2, "Dragon");
ptmt.setString(3, "M.Tech");
ptmt.executeUpdate();
} catch (ClassNotFoundException e) {
System.out.println("Class Not found Exception cought");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Closing the connection
conn.close();
ptmt.close();
System.out.println("Database Updated Successfully");
System.out.println("Disconnected from database");
}
}
}
| MySQL Insert PreparedStatement Example. Connected to the database Database Updated Successfully Disconnected from database |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.