Error: MySQLSyntaxErrorException in a java-based web app [duplicate] - java

This question already has answers here:
Passing table name as parameter of prepared statement [duplicate]
(3 answers)
Closed 6 years ago.
public List<User> arrangeUsers(String option) {
String query = "";
if (option.equals("lastNameAsc")) {
query = "SELECT * FROM ? ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query = "SELECT * FROM ? ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
if (searchList.size() > 0) {
stmt.setString(1, "search_results");
searchList.clear();
listChoice = true;
} else {
stmt.setString(1, "users");
users.clear();
listChoice = false;
}
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
The above method returns an error:
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 ''users' ORDER BY lastName DESC' at line 1 " error.
The method is supposed to arrange a list of users (a table) according to the order required by the client. Any suggestions what is the reason for the error message? I am ready to provide any additional details if necessary.

A table name can't be used as a parameter. It must be hardcoded. You can do something like:
public List<User> arrangeUsers(String option) {
String query = "SELECT * FROM ";
if (searchList.size() > 0) {
query += "search_results ";
searchList.clear();
listChoice = true;
} else {
query += "users ";
users.clear();
listChoice = false;
}
if (option.equals("lastNameAsc")) {
query += "ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query += "ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query += "ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query += "ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
Hope it helps.

Related

SQLException: query does not return results

I am doing a project in Java Swing and using SQLite as my database.
This is the function I wrote for deleting a record from the Room table in my database.
public void Delete() {
String room_code = jTextField5.getText();
String sql = "DELETE FROM Room WHERE room_code = '" + room_code + "'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Room Deleted Successfully");
}
else {
JOptionPane.showMessageDialog(null, "Invalid Room Code");
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
However, I am met with the following Exception: SQLException: query does not return results.
I have tried to use pst.executeUpdate() as suggested in other answers but it says "int cannot be converted into resultset".
A DELETE statement does not return a result set. You should call method executeUpdate rather than method executeQuery.
Also, you can use place holders with a PreparedStatement.
Also you should use try-with-resources
Consider the following code.
public void Delete() {
String room_code = jTextField5.getText();
String sql = "DELETE FROM Room WHERE room_code = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(room_code);
int count = ps.executeUpdate();
if (count > 0) {
JOptionPane.showMessageDialog(null, "Room Deleted Successfully");
}
else {
JOptionPane.showMessageDialog(null, "Invalid Room Code");
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}

Can i have two connection statement in a single button action performed using java swing.?

My complete code to access data from two different databases using single hive jdbc driver. I get sql exception on next database connection, before that it works perfectly. Kindly, suggest me some solution to further process. Where as next prepared statement query throws sql exception. But doing on a separate button action it works fine, while i'm doing in a single action it throws error.
String s1 = jTextField1.getText();
String s2 = jTextField2.getText();
String s3 = jTextField3.getText();
String s4 = new String(jPasswordField1.getPassword());
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/twitter_db", "arunachalam", "");
Statement st = con.createStatement();
String sql = "select dbname,tbname from check where userid='" + s3 + "'and tbname='" + s2 + "'";
String sql1 = "select userid,password from user_reg where userid='" + s3 + "'";
ResultSet rs = st.executeQuery(sql);
try {
PreparedStatement ps = con.prepareStatement(sql1);
ResultSet rs1 = ps.executeQuery();
while (rs.next() && rs1.next()) {
if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
jSeparator1.setVisible(true);
jScrollPane1.setVisible(true);
try {
Connection con1 = DriverManager.getConnection("jdbc:hive2://localhost:10000/" + s1, "arunachalam", "");
ArrayList<Tweet> list = new ArrayList<Tweet>();
String ve = "select id,created_at,source,favorited,retweet_count,retweeted_status,entities,text,user,in_reply_to_screen_name from " + s2;
PreparedStatement ps1 = con1.prepareStatement(ve);
ResultSet rs2 = ps1.executeQuery();
Tweet tweet;
while (rs2.next()) {
tweet = new Tweet(rs.getLong("id"), rs.getString("created_at"), rs.getString("source"), rs.getBoolean("favorited"), rs.getInt("retweet_count"), rs.getString("retweeted_status"), rs.getString("entities"), rs.getString("text"), rs.getString("user"), rs.getString("in_reply_to_screen_name"));
list.add(tweet);
String[] columnName = {"Tweet_ID", "Created_At", "Source", "Favorited", "Retweet_Count", "Retweeted_Status", "Entities", "Text", "User", "Screen_Name"};
Object[][] twt = new Object[list.size()][10];
for (int i = 0; i < list.size(); i++) {
twt[i][0] = list.get(i).gettweetid();
twt[i][1] = list.get(i).getcreated();
twt[i][2] = list.get(i).getsource();
twt[i][3] = list.get(i).getfavor();
twt[i][4] = list.get(i).getcount();
twt[i][5] = list.get(i).getstatus();
twt[i][6] = list.get(i).getentities();
twt[i][7] = list.get(i).gettext();
twt[i][8] = list.get(i).getuser();
twt[i][9] = list.get(i).getscreen();
TheModel model = new TheModel(twt, columnName);
jTable1.setModel(model);
jTable1.setRowHeight(20);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
break;
} else if ((!rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Database Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (!rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Table Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (!rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Password is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((!rs1.getString("userid").equals(s3)) && (rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "User ID is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else {
JOptionPane.showMessageDialog(null, "Access Denied", "Error", JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
} catch (Exception e) {
showMessageDialog(null, e);
}
To be responsive, as the application would freeze during actionPerformed use
invokeLater.
Yes separate connections for instance with different users, one for reading only, one for admin tasks, is quite possible. However I did not see calls to close().
(Also a single-user (such as an embedded) database might not do.)
To automatically close connection, statement and result set use try-with-resources: try (DECLARATION; ... ; DECLARATION) { ... } - saves a lot.
The explicit class loading with Class.forName no longer is needed for current drivers.
// Java 8
SwingUtilities.invokeLater(() -> {
String sql = "select dbname, tbname from check where userid=? and tbname=?";
try (Connection con = DriverManager.getConnection(
"jdbc:hive2://192.168.1.13:10000/twitter_db", "arunachalam", "");
PreparedStatement st = con.prepareStatement(sql)) {
st.setString(1, s3);
st.setString(2, s2);
try (ResultSet rs = st.executeQuery()) {
if (rs.next()) {
List<Tweet> list = new ArrayList<>();
String hive = "select id,created_at,source,favorited,retweet_count,"
+ "retweeted_status,entities,text,user,in_reply_to_screen_name from "
+ s2;
try (Connection con1 = DriverManager.getConnection(
"jdbc:hive2://localhost:10000/"+s1, "arunachalam", "");
PreparedStatement ps1 = con1.prepareStatement(hive);
ResultSet rs2 = ps1.executeQuery()) {
...
});

how get insterted data from mysql as it inserted

i have built quiz web project.
i want to insert below mentioned test question into database. i am writing this question in html textarea, then getdata from html with inner.html :
but when i select this question from database it looks like that, it is hard readable, carelessly written:
help me make above mentioned tests readable.
my sql insert code :
public void addtest(TestModel test) throws Exception {
Connection c = null;
PreparedStatement ps = null;
String sql = "INSERT INTO TEST_TABLE (QUESTION,A,B,C,D,E,QUESTION_TYPE,SCORE,SUBJECT, CORRECT, Variant) " +
" VALUES (?,?,?,?,?,?,?,?,?,?,?) ";
try {
c= DbHelper.getConnection();
if(c != null) {
ps = c.prepareStatement(sql);
ps.setString(1,test.getQuestion());
ps.setString(2,test.getOptionA());
ps.setString(3,test.getOptionB());
ps.setString(4,test.getOptionC());
ps.setString(5,test.getOptionD());
ps.setString(6,test.getOptionE());
ps.setString(7,test.getQuestionType());
ps.setLong(8,test.getScore());
ps.setLong(9,test.getSubjectId());
ps.setString(10,test.getCorrectOption());
ps.setInt(11,test.getVariant());
ps.execute();
} else {
System.out.println("Connection is null");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtility.close(c,ps,null);
}
}
my sql select code :
public TestModel getquestionlist(long firstpage,int variant) throws Exception {
TestModel testdata = new TestModel();
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql =" SELECT TE.ID,TE.QUESTION,TE.A,TE.B,TE.C,TE.D,TE.E,TE.F,TE.G,TE.QUESTION_TYPE,TE.SCORE,S.NAME as Subject,TE.CREATE_DAY,TE.CORRECT, d.value, TE.Variant FROM TEST_TABLE TE " +
"INNER JOIN SUBJECT S ON S.ID = TE.SUBJECT " +
"inner join dictionary d on d.ID = TE.Variant " +
"WHERE TE.ACTIVE =1 AND S.ACTIVE =1 AND TE.Variant = ? " +
"LIMIT ?,1; ";
try {
c = DbHelper.getConnection();
if (c != null) {
ps = c.prepareStatement(sql);
ps.setInt(1,variant);
ps.setLong(2, firstpage);
rs = ps.executeQuery();
while (rs.next()) {
testdata.setId(rs.getLong("ID"));
testdata.setQuestion(rs.getString("QUESTION"));
testdata.setOptionA(rs.getString("A"));
testdata.setOptionB(rs.getString("B"));
testdata.setOptionC(rs.getString("C"));
testdata.setOptionD(rs.getString("D"));
testdata.setOptionE(rs.getString("E"));
testdata.setOptionF(rs.getString("F"));
testdata.setOptionG(rs.getString("G"));
testdata.setQuestionType(rs.getString("QUESTION_TYPE"));
testdata.setScore(rs.getLong("SCORE"));
testdata.setTestSubject(rs.getString("Subject"));
testdata.setCreateDate(rs.getDate("CREATE_DAY"));
testdata.setCorrectOption(rs.getString("CORRECT"));
testdata.setVariant(rs.getInt("Variant"));
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtility.close(c, ps, rs);
}
return testdata;
}
You can use <br/> to break line :
"1: public class WaterBottle { <br/>"
So in the moment of getting the result you can concatenate your result with <br/> for example :
testdata.setQuestion(rs.getString("QUESTION") + "<br/>");

SQL injections (java)

I am trying to figure out a way to see if the sql injection is correct based on the user input and if so, delete that row.
For instance the user enters 123 for an idNumber, if that number exits, the the sql statement "select * from student where idNumber = " + idNumber + ";" would be correct.
When it is verified that it is correct, I would then use another statement to delete the query.
My main issue is figuring out how to verify it is correct.
Thanks!
public static void CheckStudent(Connection con, String idNumber) throws SQLException {
Statement stmt = null;
String query = "select * from student where idNumber = " + idNumber + ";"
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (!rs.isBeforeFirst() ) {
//Here is where you do the check
System.out.println("No data");
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}

to check whether the search element isn't available in DB

I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}

Categories