PreparedStatement troubles in Java [duplicate] - java

This question already has answers here:
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 7 years ago.
This is my method:
#Override
public void deleteOneRecord(String tableName, String id) throws ClassNotFoundException, SQLException{
// Validate the parameters here.
// String sql = "DELETE FROM " + tableName + " WHERE " + column + "=" + value;
String pKeyColumnName = "";
// Statement stmt = conn.createStatement();
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rs = dmd.getPrimaryKeys(null, null, tableName);
while(rs.next()){
pKeyColumnName = rs.getString("COLUMN_NAME");
System.out.println("PK column name is " + pKeyColumnName);
}
//String sql = "delete from " + tableName + " where " + pKeyColumnName + "=" + id;
String sql2 = "delete from ? where ?=?";
PreparedStatement pstmt = conn.prepareStatement(sql2);
pstmt.setString(1, tableName);
pstmt.setString(2, pKeyColumnName);
pstmt.setInt(3, Integer.parseInt(id));
pstmt.executeUpdate();
}
This is my test main:
public static void main(String[] args) throws ClassNotFoundException, SQLException {
DBStrategy db = new MySqlDBStrategy();
db.openConnection("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/book", "root", "admin");
System.out.println(db.findAllRecords("author", 0).toString());
db.deleteOneRecord("author", "2");
System.out.println(db.findAllRecords("author", 0).toString());
db.closeConnection();
}
The db object works, open connection works, my find all records method works,
then my deleteOneRecord blows up. I get this error:
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 ''author' where 'author_id'=2' at line 1
Now my syntax hasn't changed, I was running this code as just a Statement no problem a few minutes ago, so I must be using PreparedStatement incorrectly somehow.
Any help would be appreciated greatly.

I don't believe you can use parameters for the table name or the column name. You'll have to concatenate those into the string. Depending on where they come from, be careful about SQL injection vulnerabilities!

Related

# with sql and java

when i tried to get email from my DB on intellij it always shows me that the email is something like this: com.mysql.cj.jdbc.result.ResultSetImpl#4c89299.
how could i fix it.
and that's the code.
DBHandler:
public ResultSet getAllmessages(String reciever) throws SQLException, ClassNotFoundException {
String query = "SELECT * FROM " + Const.MESSAGES_TABLE + " WHERE " + Const.MESSAGES_RECIEVER + "=?";
PreparedStatement preparedStatement = getDbConnection().prepareStatement(query);
preparedStatement.setString(1, reciever);
ResultSet resultSet = preparedStatement.executeQuery();
return resultSet;
}
where i take the email:
DBHandler databasehandler = new DBHandler();
ResultSet maild = databasehandler.getAllmessages(databasehandler.getMail(indexController.userId).toString().trim());
ResultSet resultSet = databasehandler.getAllmessages((maild).toString().trim())
After you get ResultSet object you have to get values like this.
resultSet.getString("COLUMN_NAME1");
resultSet.getInt("COLUMN_NAME2");

Java MySQL executeUpdate SQLSyntaxErrorException [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I just started to work with MySQL in Java, I am trying to update existing data in my database. The main purpose is to create a counter, there will update an int in the database when an action has been done.
In this case, I am trying to update the daily_search_count by increasing the integer when the code is compiling. Below you can see a picture of my DB data:
data within the database
The code I have written is intended to increase the "daily_search_count" by 1 each time the code is running. But unfortunately I get the following error:
Exception in thread "main" java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''accounts' set 'daily_search_count' = '4' where 'id' = '1'' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1396)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1051)
at Database.main(Database.java:29)
I can't see what is wrong with my code as you can see below:
import java.sql.*;
public class Database {
public static void main(String[] args) throws Exception {
String host = "jdbc:mysql://localhost:3306/presearch";
String username = "root";
String password = "";
String query = "select * from accounts";
Connection con = DriverManager.getConnection(host, username, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
String userData = "";
while (rs.next()) {
if (rs.getInt(4) < 33) {
userData = rs.getInt(1) + " : " + rs.getString(2) + " daily search count : " + rs.getInt(4);
System.out.println(userData);
int counter = rs.getInt(4) + 1;
PreparedStatement updatexdd = con.prepareStatement("update 'accounts' set 'daily_search_count' = '" + counter + "' where 'id' = '" + rs.getInt(1) + "'");
int updatexdd_done = updatexdd.executeUpdate();
}
}
st.close();
con.close();
}
}
I hope someone can see what I am doing wrong.
Thanks in advance!
You have some problems in your code you have to avoid :
name of table and columns should not be between two quotes 'accounts'
make sure to use placeholder(?) to specify your attribute in the query with PreparedStatement
make sure to close the connection and statement in finally block instead
I note also that all you need is just one query
Your code should look like this :
public static void main(String[] args) throws Exception {
String host = "jdbc:mysql://localhost:3306/presearch";
String username = "root";
String password = "";
String query = "update accounts set daily_search_count = daily_search_count + 1 where daily_search_count < 33";
try (Connection con = DriverManager.getConnection(host, username, password);
PreparedStatement updatexdd = con.prepareStatement(query)) {
int updatexdd_done = updatexdd.executeUpdate();
}
}
In my code I use The try-with-resources Statement which support AutoCloseable and Closeable Interface which mean you don't need to close the connection or the statement.

Writing a txt file to mySQL database

I'm currently trying to write a txt file to a mySQL database through a Java program. My database connects correctly through a JDBC driver and I can create tables etc through the program. However when I try to read the text file in I get this error message
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''FName' , 'SName' , 'DOB') VALUES ('John' , 'McCullough' , '270696')' at line 1
I can't find an error in my SQL code. Here is the rest of the code from the class. Any help would be greatly appreciated.
try (Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
FileReader file1 = new FileReader("resources/Test.txt");
BufferedReader buffer1 = new BufferedReader(file1);
String read;
while ((read = buffer1.readLine()) != null) {
String[] row = read.split(",");
String fName = row[0];
String sName = row[1];
String DOB = row[2];
String insert = "INSERT INTO chessleague.table1 ('FName' , 'SName' , 'DOB') VALUES ('" + fName + "' , '" + sName + "' , '" + DOB + "')";
ps = con.prepareStatement(insert);
ps.executeUpdate();
ps.close();
}
} catch (Exception ex) {
System.out.println(ex);
}
As mentioned in the comments, don't quote the column names.
The code heavily misuses prepared statements to execute simple SQL. The Connection Class has a createStatement() method that creates a simple statement which is meant for text form SQL commands.
Statement stmt = con.createStatement();
stmt.execute("SELECT * from test.t1");
Prepared statements expect a template that is used to create the SQL statements. Here's an example of how the insert could be done with prepared statement commands.
try (PreparedStatement ps = con.prepareStatement("INSERT INTO chessleague.table1 (FName , SName , DOB) VALUES (?, ?, ?)")) {
ps.setString(0, fName);
ps.setString(1, sName);
ps.setString(2, DOB);
ps.execute();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}

I need help selecting within a MySQL DateTime range in Java

I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception message
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 '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.
Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...

Java mysql syntax error

I get syntax error to mysql insert statement. May I know how to correct this error ?
user=txtuser.getText();
char[] pass=jPasswordField1.getPassword();
String passString=new String(pass);
try{
Connection con = createConnection();
Statement st = con.createStatement();
**String sql = "INSERT INTO login(username,Password)"+"VALUES"+"('"user"','"passString"')";**
st.executeUpdate(sql);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Exception: "+ e.toString());
}
You're missing a few + operators:
String sql = "INSERT INTO login(username,Password) VALUES ('" + user + "','" + passString + "')";
Consider using PreparedStatement placeholders to set these parameters. This will protect you from SQL injection attacks also. Here is an example

Categories

Resources