How to use placeholder inside sql replace() in java? - java

I want to use placeholder inside sql replace function in java.
Following is the code.
import java.sql.*;
public class TestDB {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("class");
Connection con = DriverManager.getConnection("url","username","password");
PreparedStatement ps = null;
String query = "select name from image where id >= replace(?,'','','''') and id <= replace(?,'','','''') and name like ''%aa'' order by id;";
ps= con.prepareStatement(query);
ps.setString(1, "1");
ps.setString(2, "10");
ResultSet rs = null;
rs= ps.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1));
}
}
}
In ps= con.prepareStatement(query); line I am getting:
Exception in thread "main" java.sql.SQLException: An illegal character has been found in the statement.
Actually using a simple create statement it works fine. But when I use preparedstatement with placeholder it's throwing exception.
Can anyone let me know what the issue is?

Related

SQL Exception cannot issue statements that do not produce result sets- Java

public static void main(String[] args) throws Exception{
Connection con = DriverManager.getConnection(url, uname, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
String name = rs.getString("NAME");
System.out.println(name);
st.close();
con.close();
}
: When I run this code this is the error i am getting..
Exception in thread "main" java.sql.SQLException: Statement.executeQuery() cannot issue statements that do not produce result sets.
What can I do to fix this error?
In my case the solution was to downgrade from "mysql-connector-java-8.0.30" to "mysql-connector-java-8.0.18".

JAVA JDBC mySql Prepared statement Update query [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 4 years ago.
I am trying to execute the following code
package jdbclesson;
import java.sql.*;
public class PreparedQuery {
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/alien?useSSL=false";
String uname = "root";
String pass = "ma123";
String query = "UPDATE student SET username= ? where userid= ? ";
PreparedStatement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
stmt = con.prepareStatement(query);
stmt.setString(1, "tina");
stmt.setInt(2, 6);
int rs = stmt.executeUpdate(query);
System.out.println(rs);
stmt.close();
con.close();
}
}
but getting following errors
Exception in thread "main"
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '? where
userid=?' at line 1
My database has only 1 table student with 2 columns userid and username and 10 rows what m i missing
Try:
int rs = stmt.executeUpdate();
Instead of:
int rs = stmt.executeUpdate(query);
executeUpdate() runs the query of the prepared statement, which is what you want. executeUpdate(query) runs the query passed to the method. You were getting the error because you were passing an SQL with errors (contains ?).
Please try:
"UPDATE student SET username= ? ” + ” where userid= ?";
int rs=stmt.executeUpdate();

Issue in connecting MS SQL server using Java program

I am having a problem in executing a simple select statement in Microsoft Sql Server DB using a Java program. I am facing below 2 issues,
Code by using statement * Resultset - program just hungs near the executequery() method and no progress after that.
Sample code:-(Full code pasted below)
Statement sta = conn.createStatement();
String Sql3 = "select name from dbo.network";
sta.executeQuery(Sql3);
ResultSet rs=sta.getResultSet();
code with preparestatment * Resultset throws error saying
The method executeQuery() cannot take arguments on a PreparedStatement or CallableStatement
Sample Code:-
PreparedStatement ps = conn.prepareStatement(Sql3);
ResultSet rs = ps.executeQuery(Sql3);
Complete Code:-
public class DbConnectionTest {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("Entered into main method");
String userName ="***";
String password ="***";
String url ="jdbc:sqlserver://****:1433;databaseName=***";
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
System.out.println("test");
Statement sta = conn.createStatement();
String Sql3 = "select name from dbo.network";
//PreparedStatement ps = conn.prepareStatement(Sql3);
//ResultSet rs = ps.executeQuery(Sql3);
sta.executeQuery(Sql3);
//sta.getMoreResults();
//sta.getMoreResults();
ResultSet rs=sta.getResultSet();
if(rs != null)
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}catch(Exception se){
//Handle errors for JDBC
se.printStackTrace();
}
}
}
In Addition, I confirm the below,
Same query executes fine in the database.
SQL Browser Server service is running fine
TCP/IP is enabled
Credentials and the URL string are correct
sqljdbc4.jar is used.
Please help me with this issue.

Using PreparedStament of JDBC with Mysql's TableName end with '\'

I am trying to insert something into my Mysql Database, which has a table whose name end with '\'. Its name is 'abc\'.
public static void main(String[] args) throws ClassNotFoundException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection master = DriverManager.getConnection($URL,$USR,$PWD);
String st = "insert into `abc\\` (`pad`,`c`,`k`,`id`) values(?,?,?,?)";
PreparedStatement pstmt = master.prepareStatement(st);
pstmt.setInt(1, 10);
pstmt.setInt(2, 1);
pstmt.setString(3, "1");
pstmt.setString(4, "2");
pstmt.execute();
master.close();
}catch(SQLException ex){
ex.printStackTrace();
}
But it doesn't work, the problem is :
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
But, it the table's name is 'a\bc', whose backslash is not the last character, my program works well.
Can anyone help me to solve this problem? Thanks a lot.
It is working with Statement.
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String st = "insert into `abc\\` (`pad`,`c`,`k`,`d`) values(10,11,'5','6')";
Statement stmt = (Statement) con.createStatement();
stmt.execute(st);
con.close();
}

PreparedStatement throws syntax error [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 7 years ago.
Im preparing a query using PreparedStatements and it runs fine when i hardcode te query with the condition parameter.
but throws error , if the parameter is passed from setString() method.
com.mysql.jdbc.JDBC4PreparedStatement#2cf63e26: select * from linkedin_page_mess ages where company_id = '2414183' com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '?' at line 1
In the error log, above my query looks fine.
public JSONObject getLinkedInMessages(String compId)
{
linlogger.log(Level.INFO, "Called getLinkedInMessages method");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
JSONObject resObj = new JSONObject();
JSONArray tempArray = new JSONArray();
try
{
conn = InitOrGetConnection();
String query = "select * from linkedin_page_messages where company_id = ?";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, compId);
System.out.println("\n\n"+pst.toString());
rs= pst.executeQuery(query);
// process resultset logics
}
catch(Exception e)
{
System.out.println(e);
linlogger.log(Level.INFO, "Exception occured "+e.toString());
}
}
Is there anything wrong with the PreparedStatements?
Remove the parameter from
rs= pst.executeQuery(query);
change to
rs= pst.executeQuery();
If you pass query in pst.executeQuery(query); as parameter then this passed query string take priority over the query string you passed in conn.prepareStatement(query); and since in query(select * from linkedin_page_messages where company_id = ?) you dint pass parameter you get the error.
remove the parameter in this line:
rs= pst.executeQuery(query);
It must be
rs= pst.executeQuery();
Because the statement is prepared at PreparedStatement pst=conn.prepareStatement(query);
execute(String sql) is inherited from Statement and will execute the satement (sql) without prepared it.

Categories