In this example we will show how to create a SQL using JDBC PreparedStatement in Java.
Source Code
package com.beginner.examples;
import com.mysql.jdbc.Driver;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class PreparedStatementExample {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
//database connection
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql", "root", "");
List result = new ArrayList();
// sql statement
String sql = "SELECT host from user " +
" WHERE user = (?) ";
try
{
// PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "root");
// execute the sql statement
ResultSet rs = ps.executeQuery();
while (rs.next())
{
System.out.println(rs.getString("host"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
127.0.0.1
::1
localhost
References
Imported packages in Java documentation: