I have sql query which is shown below its a select statement I want to pass dynamically the values but I am not aware how can we do it .here I want to pass product and location dynamically
can anyone help in this ..
public static ResultSet RetrieveData() throws Exception {
PreparedStatement statement;
String sql = "select * FROM Courses WHERE "
+ "product = product? "
+ "and location = location? ";
System.out.println(sql);
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost:3306/wave1_build";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "root");
statement = con.prepareStatement(sql);
ResultSet rs = statement.executeQuery(sql);
return rs;
One approach is to use plain ? placeholders along with the appropriate setters to bind values:
String sql = "SELECT * FROM Courses WHERE product = ? AND location = ?";
statement = con.prepareStatement(sql);
statement.setString(1, "some product");
statement.setString(2, "some location");
// NOTE: executeQuery() when used with prepared statements does NOT take any parameters
ResultSet rs = statement.executeQuery();
Related
I have a small problem. I wrote a method in which I have an SQL query that should output a correct string after 2 parameters. When debugging, however, the result is not the right element. I don't know why this happens.
public static String findRightTemplate(String user_name, int template_id)
throws Exception {
Connection conn = DriverManager.getConnection(
"xxx", "xxx", "xxx");
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery(
"SELECT template FROM templates " +
"where template_id=template_id AND user_name=user_name"
);
String temp="";
while(rs.next())
{
temp=rs.getString("template");
}
rs.close();
st.close();
conn.close();
I ask for the username and template_id and I just want to get an element out of the template column.
The SQL query is correct. I've already tested that. But it seems that the query runs through all elements with the same username. As a result, I only get the last element and not the right one.
UPDATE
Currently you do not use the method parameters inside your query. As already suggested you should use a PreparedStatement to fix that. You should basically do the following:
public static String findRightTemplate(String userName, int templateId) throws SQLException {
try (final Connection connection = DriverManager.getConnection("...")) {
final PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT template " +
"FROM templates " +
"WHERE user_name = ? " +
"AND template_id = ? " +
"LIMIT 1"
);
preparedStatement.setString(1, userName);
preparedStatement.setInt(2, templateId);
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getString(1);
}
}
return null;
}
If you do not use a PreparedStatement and build the query manually as suggested in the comments your application could be vulnerable to SQL injection attacks.
String get_date = check_in_date.getText();
String get_customer_no = customer_no.getText();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rst = null;
try{
String driver ="com.mysql.jdbc.Driver";
String url ="jdbc:mysql://localhost:3306/hotel";
String userid ="root";
String password ="tushar11";
Class.forName(driver);
conn = DriverManager.getConnection(url,userid,password);
pstmt = conn.prepareStatement("select occupantdetails.customer_name,
hoteldetails.service_detail, hoteldetails.cab_no from
occupantdetails JOIN hoteldetails ON
occupantdetails.customer_no=hoteldetails.customer_no" );
pstmt.setString(1, get_customer_no);
rst = pstmt.executeQuery();
while(rst.next()){
txt_customer_name.setText(rst.getString("customer_name"));
txt_room_no.setText(rst.getString("service_detail"));
txt_cab_no.setText(rst.getString("cab_no"));
}
}
I am new to this. As i am fetching the details it is showing the parameter error and i cannot solve this. I think i have written the right query and there might be mistake in java code.
I guess your statement should be something like
"SELECT *
FROM YourTable
WHERE customer_no = ?"
Check the tutorial for prepared statements
Firstly, I'm reading the product name and number of products from user using jTextFields. For that product I read the product id and price from database using sql query. But in the below code I display the product price in a jtextField but while running tha file I get query executed successfully but I'm not getting anything in the jtextField.
And please check the sql query and resultset use,
table name is "item" and database name is "myshop",
I declared variables globelly and this code is in a jButton's 'ActionPeformed" part.
String item_name=name.getText();
int item_no=Integer.parseInt(no.getText());
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
java.sql.Statement stmt=con.createStatement();
if (stmt.execute(sql)) {
rs = stmt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
} else {
System.err.println("select failed");}
int idIndex = rs.findColumn("id");
int priceIndex = rs.findColumn("price");
while(rs.next()){
item_id=rs.getInt(idIndex);
item_price=rs.getInt(priceIndex);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
This line should be
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
like this
String sql="SELECT id,price FROM item WHERE item.name='"+item_name+"'";
Use a PreparedStatement so you don't have to worry about delimiting all the variables:
String sql="SELECT id, price FROM item WHERE item.name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, item_name);
ResultSet rs = stmt.executeQuery();
Then the prepared statement will replace the variable for you with the proper quotes.
you would need to take item_name as param and put in quotes,
String sql="SELECT id,price FROM item WHERE item.name='"+ item_name+"'";
Try to avoid this type of mistake by using PreparedStatement
String sql="SELECT id,price FROM item WHERE item.name=?";
PreapredStatement ps = con.prepareStatement(sql);
ps.setString(1,item_name);
ResultSet rs = ps.executeQuery();
Use of PreparedStatement also prevent SQL injection attack.
try this code .
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
PreparedStatement pt=con.prepareStatement("SELECT id,price FROM item WHERE item.name=?");
pt.setString(1,"item_name");
ResultSet rs;
if(pt.execute())
{
rs=pt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
}
else {
System.err.println("select failed");
}
while(rs.next()){
item_id=rs.getInt(1);
item_price=rs.getInt(2);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2
}
First, you need an reader, like this
private static void reader() throws SQLException {
DataBaseName db = new DataBaseName ();
names = db.getNames();
}
This is my code:
public static List GetList(String myname) {
.
.
ResultSet result = stmt.executeQuery("SELECT * FROM authors WHERE name = ?");
result.setString(myname);
}
I want to select where name = myname (myname is the input of the function).
I tried also something like:
WHERE name = #myname
but it doesn't work :/
You don't set the value on the result but on the statement:
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM authors WHERE name = ?");
pstmt.setString(1, myname);
ResultSet result = pstmt.executeQuery();
Well, a better way to go is to use PreparedStatement, to avoid SQL Injection: -
PreparedStatement stmt = con.prepareStatement("SELECT * FROM authors WHERE name = ?");
stmt.setString(1, myname);
ResultSet res = stmt.executeQuery();
However, just to solve your issue, you can use String Concatenation: -
stmt.executeQuery("SELECT * FROM authors WHERE name = '" + myname + "'");
If I'm not mistaken, you'd be better off with prepared statements here:
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM authors WHERE name = ?");
stmt.setString(1, myname);
ResultSet result = stmt.executeQuery();
try this:
ResultSet result = stmt.executeQuery("SELECT * FROM authors WHERE name = " + myname);
I'm trying to make my validation class for my program. I already establish the connection to the MySQL database and I already inserted rows into the table. The table consists of firstName, lastName and userID fields. Now I want to select a specific row on the database through my parameter of my constructor.
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class Validation {
private PreparedStatement statement;
private Connection con;
private String x, y;
public Validation(String userID) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
statement = con.prepareStatement(
"SELECT * from employee WHERE userID = " + "''" + userID);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
x = rs.getString(1);
System.out.print(x);
System.out.print(" ");
y = rs.getString(2);
System.out.println(y);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
But it doesn't seem work.
You should use the setString() method to set the userID. This both ensures that the statement is formatted properly, and prevents SQL injection:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
There is a nice tutorial on how to use PreparedStatements properly in the Java Tutorials.
If you are using prepared statement, you should use it like this:
"SELECT * from employee WHERE userID = ?"
Then use:
statement.setString(1, userID);
? will be replaced in your query with the user ID passed into setString method.
Take a look here how to use PreparedStatement.
There is a problem in your query..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
You are using Prepare Statement.. So you need to set your parameter using statement.setInt() or statement.setString() depending upon what is the type of your userId
Replace it with: -
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Or, you can use ? in place of named value - :userId..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
Do something like this, which also prevents SQL injection attacks
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
You can use '?' to set custom parameters in string using PreparedStatments.
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
If you directly pass userID in query as you are doing then it may get attacked by SQL INJECTION Attack.