PreparedStatement nsert logical operation (=,<,>=,<,>=) in my sql - java

I want to insert logical operations (=,<,>=,<,>=) in my sql
try {
String sql = "SELECT id,name,date_N FROM LECTEUR WHERE date_N ?,?";
Connection con = DBinfo.getConnection();
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, operationCB.getValue());
ps.setString(2, date1.toString());
ResultSet resultSet = ps.executeQuery();
output:
Incorrect syntax near '#P0'.

You can only insert values as parameters of the PreparedStatement.
If you want the operation to be dynamic, use a StringBuilder to build the query String:
StringBuilder sql = new StringBuilder();
sql.append("SELECT id,name,date_N FROM LECTEUR ");
sql.append("WHERE date_N ");
sql.append(operationCB.getValue());
sql.append(" ?");
Connection con = DBinfo.getConnection();
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql.toString());
ps.setString(1, date1.toString());
ResultSet resultSet = ps.executeQuery();

You cannot bind a logical operator to a prepared statement using a ? placeholder. One workaround would be to maintain separate queries for the various logical operations:
Map<String, String> queryMap = new HashMap<>();
queryMap.put("=", "SELECT id, name, date_N FROM LECTEUR WHERE date_N = ?");
queryMap.put(">", "SELECT id, name, date_N FROM LECTEUR WHERE date_N > ?");
// etc.
try {
String sql = queryMap.get(operationCB.getValue()); // fetch the appropriate statement
Connection con = DBinfo.getConnection();
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setDate(1, date1);
ResultSet resultSet = ps.executeQuery();
} catch (SQLException e) {
// handle exception
}

Related

How to pass multiple parameters in sql query using Java?

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();

Insert multiple data (List) in MySQL using JDBC

I am trying it from last 2 hour i dont know what is going wrong. also let me know how could i test if the connection is successfull or not.. it is for now.. but still i wanted to know..
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?)'
My code:
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/medicinedb";
static final String USER = "root";
static final String PASS = "";
static final String DRIVER = "com.mysql.jdbc.Driver";
public boolean saveMedicine(List<MedicineName> medicineName) throws ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
for (MedicineName element : medicineName) {
String sql;
sql = " insert into medicinename (name, pgurl)" + " values
( ?, ?)";
System.out.println(conn);
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
stmt.executeUpdate(sql);
}
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
Why you are using Statement and Prepared statement. You are performing operations with Statement. Thus it does not have value. Remove the Statement
stmt = conn.createStatement();
And do the following
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
//stmt.executeUpdate(sql);
preparedStmt .executeUpdate(sql);
use
String sql = "insert into medicinename (name, pgurl) values (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString (1, element.getName());
preparedStmt.setString (2, element.getPgurl());
preparedStmt.executeUpdate();
you should delete executeUpdate(sql); to executeUpdate();
You mix between your stm and preparedStmt, you have to execute preparedStmt and not stm.
Another thing when you want to executing multiple statements as one unit, its good to work with Statement Batching instead for example :
PreparedStatement preparedStmt;
String sql;
conn.setAutoCommit(false);
for (MedicineName element : medicineName) {
sql = "insert into medicinename (name, pgurl) values (?, ?)";
System.out.println(conn);
preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
preparedStmt.addBatch(sql);
}
preparedStmt.executeBatch();
conn.commit();

How to change password column in mysql

String user = request.getParameter("uname");
String pwd = request.getParameter("pass");
String pwd1 = request.getParameter("pass");
String pwd2 = request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/logindb";
Connection con = DriverManager.getConnection(url, "root", "root");
String sql = "select * from register";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
ResultSet rs = ps.executeQuery();
if(rs.next())
{
sql = "update register set pass=? where uname=? ";
ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
ps.executeUpdate();
out.println("password changed");
}
}
catch(Exception e)
{
out.println(e);
}
This Is my code and it will show me an error like this
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).**
Here:
String sql = "select * from register";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
You are trying to set parameters that aren't there. Looks like a copy-and-paste error. Those last 2 lines shouldn't be there.

Exception in prepared statement

Following is the code.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:cse");
//Statement stmt;
ResultSet rset;
//stmt = conn.createStatement();
String sql = " Select * from registration where id=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, "101");
rset = pst.executeQuery(sql);
while (rset.next()) {
arr.add(rset.getInt("id"));
arr.add(rset.getString("first"));
arr.add(rset.getString("last"));
arr.add(rset.getInt("age"));
}
System.out.println(arr);
pst.close();
conn.close();
For the above am getting "Error: java.sql.SQLException: Driver does not support this function". What might be the problem?
You are misusing the PreparedStatement interface. When using PreparedStatements, you should prepare the statement with your query, bind all necessary parameters and then execute it without any SQL - this will cause the statement to execute the previously prepared SQL statement:
String sql = "Select * from registration where id=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, "101");
rset = pst.executeQuery(); // Note - No args in the executeQuery call

Retrieving a specific value from mysql database based on parameters

I want to retrieve a users name from the username and password that they have entered into textfields. i want to pass these values as parameter to method which will then identify the users name for printout. please help. something like this...
public void getUser(String username, String password)throws SQLException{
String qry = "SELECT UserName From USER....";
Connection con = null;
PreparedStatement stmt = null;
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.executeUpdate();
If not is an update or an insert, don't use executeUpdate()
You must use executeQuery().
Try this:
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT UserName From USER where username=? and password=?";
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("UserName"));
}
...
Regards
Assuming that you want to get the user's full name from db and your table structure is something like this:
fullname | username | password
you could do the following:
Connection c = null;
PreparedStatement s = null;
try {
c = DriverManager.getConnection("URL");
s = c.prepareStatement("SELECT fullname FROM user WHERE username=? and password=?");
s.setString(1, username);
s.setString(2, password);
ResultSet rs = s.executeQuery();
if(rs.next())
return rs.getString("fullname");
return null; // no user found!
} catch(SQLException e) {
System.err.println(e.getMessage());
} finally {
// close s and c
}
Note: This assumes that the password that is passed to the method is in the same "form" as it is stored in db (i.e. either plain text or hashed (+salted))
try this its very simple example
private boolean validate_login(String id,String password) {
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}

Categories