PreparedStatement सिंटैक्स
String query = "select yourColumnName from yourTableName where name = ?"; PreparedStatement ps = (PreparedStatement) con.prepareStatement(query); ps.setString(columnIndex, yourValue);
टेबल और डेटा
mysql> create table demo37 (id int not null auto_increment primary key, name varchar(200));
mysql> insert into demo37(name) values('John'), ('Bob'), ('John'), ('Chris'), ('David'), ('John'), ('Mike');
पूर्ण Java कोड उदाहरण
import java.sql.*;
public class PrepareStatementDemo {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
String query = "select name from demo37 where name = ?";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.setString(1, "John");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) { e.printStackTrace(); }
}
}
आउटपुट
John John John
लाभ: SQL इंजेक्शन रोकथाम, प्रदर्शन (प्लान कैशिंग), कोड पठनीयता।