java.sql.SQLException: Query does not return results
This is the error I get when running my code.
I am making a tic-tac-toe game to run off of a database. I'm making an empty board with this code.
Any ideas of why the database is not being updated??
//INSERT SPACE
String space1 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space2 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space3 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space4 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space5 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space6 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space7 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space8 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space9 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
/**
* Inserts empty space into space 1
*/
try {
PreparedStatement preparedStatement = connectDatabase.getConnection().prepareStatement(space1);
preparedStatement.setInt(1,0);
preparedStatement.setInt(2,0);
preparedStatement.setString(3, "e");
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
You should use preparedStatement.executeUpdate() instead. See the docs here.
The method .executeQuery() is only used for SELECT operations, or in general for any queries that return something. If, instead, you want to modify your database, you must use .executeUpdate() instead.
ResultSet resultSet = preparedStatement.executeUpdate();
^^^^^^
ExecuteUpdate is the method to use for non-results-returning DML.
Related
I want to insert the product the user selected into a table called cart which has two columns: cart_id and item_id_FK both are foreign keys. User_id and id are passed in the constructor and then inserted into cart_id and item_id_fk.
No errors are showing in the code, I double checked the connection username and password, everything works fine except for the cart table.
I tried putting a try and catch statement inside and repeating the steps it didn't work.
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch
Change executeQuery to executeUpdate:
executeQuery(sql3)
to
executeUpdate(sql3)
I believe integers don't need the ' ' around them to be inserted, you may try removing those as well. It may be mistaking them as characters or something similiar.
Otherwise if neither of those above fixes work, try something like this:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
I'm learning to work with mysql database and now trying to populate statement with text from textfield.
The program is phone book and strings are name, surname and telephone number which must be writen in textfield and then added to statement for import in database.
So, for now I have this, but not working because statement dont even recognize strings as value.. any ideas what to use/write?
if("Potvrdi".equals(buttonLabel)) {
String ime = a.getText();
String prezime = b.getText();
String broj = c.getText();
Connection conn = dc.connect();
Statement st = (Statement) conn.createStatement();
st.executeUpdate("INSERT INTO imenik VALUES (ime,prezime,broj)");
conn.close();
}
Using prepare statement,
String insertTableSQL = "INSERT INTO imenik VALUES (?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
preparedStatement.setString(1, ime);
preparedStatement.setString(2, prezime);
preparedStatement.setString(3, broj);
// execute insert
preparedStatement .executeUpdate();
This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 4 years ago.
Sql query how to pass the id from department table using the department name to the user table using the department id
here in department table dept_id is primary key
and dept_id in user table is foreign key
how to select the dept_id using department_name from the department table and store the value in the user table
try{
Connection con = DBconnect.getConnection();
//selecting the dpartment
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
String s11=comboboxdeptid.getItems().toString();
ResultSet rs=ps.executeQuery();
if(rs.next()==true)
{
if(rs.getString("DEPARTMENT_NAME").equals(comboboxdeptid.getSelectionModel().toString()))
rs.getString("DEPARTMENT_CODE");
}
//second stmt
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
String s12 = nameid.getText();
String s13 = Firstnameid.getText();
String s14 = Lnameid.getText();
String s15 = desigid.getText();
String s16 = comboboxdeptid.getItems().toString();
String s17 = addrsid.getText();
String s18 = passwordid.getText();
ps.setString(1, s12);
ps.setString(2, s13);
ps.setString(3, s14);
ps.setString(4, s15);
ps.setString(5, s17);
ps.setString(6, s18);
ps.setString(7, s11);
ps.setString(8, "abc");
ps.execute();
ResultSet rs1=ps1.executeQuery();
//third stmt
String sql2 = "update security_qa_info set SECURITY_QUESTION=?, SECURITY_ANSWER=? where USER_ID=?";
PreparedStatement ps2 = con.prepareStatement(sql2);
String s19 = securityquestionid.getSelectionModel().getSelectedItem().toString();
String s20 = answerid.getText();
while(rs2.next()==true)
{
if(rs2.getString("USER_NAME").equals(nameid.getText()))
{
rs2.getString("USER_ID");
ps2.setString(1, s16);
}
}
ps2.setString(2, s19);
ps2.setString(3, s20);
ps2.executeUpdate();
showMessageDialog(null, "Registration Successful");
}catch(Exception e){
// showMessageDialog(null, e);
e.printStackTrace();
}
Parent fxml = FXMLLoader.load(getClass().getResource("/com/abc/fxml/LoginPage.fxml"));
pane2.getChildren().setAll(fxml);
} else {
showMessageDialog(null, "Passwords don't match!");
}
}
ps = prepared statement for SELECT query:
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
ps1 = prepared statement for INSERT statement:
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
Using the wrong prepared statement:
ps.setString(1, s12);
A suggestion - if you call the first prepared statement 'selectDepartmentDetails' and the second 'insertUserInfo', it is less likely you will run into this.
Hi i am trying to insert the values in to mysql table. i am trying this code.
i have assigned values to variable and i want to pass that variable to that insert statement.
Is this correct?
code
int tspent = "1";
String pid = "trng";
String tid = "2.3.4";
String rid = "tup";
String des = " polish my shoes!";
INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');
here is what i have tried, but i am not able to insert values
try
{
conn=DBMgr.openConnection();
String sqlQuery = "INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');";
st = conn.createStatement();
rs = st.executeQuery(sqlQuery);
}
You should use executeUpdate() method whenever your query is an SQL Data Manipulation Language statement. Also, your current query is vulnerable to SQL Injection.
You should use PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
Then set the variables at those index:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
Try this,
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String uname="username";
String pass="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,uname,pass);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"')");
Use a PreparedStatement and set the values using its setXXX() methods.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO `time_entry`
(pid,tid,rid,tspend,description) VALUE
(?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();
import java.sql.*;
class Adbs1{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rk","root","#dmin");
//here rk is database name, root is username and password
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values('rk11','Irfan')");
// stmt.executeUpdate("delete from emp where eid ='rk4'");
//stmt.executeUpdate("update emp set ename='sallu bhai' where eid='rk5'");
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
I am inserting values in a Mysql database from java file using -
String query = "INSERT INTO genes (sent, title) VALUES ('"+sent+"','"+title+"')";
Statement stmt = con.createStatement();
int rs = stmt.executeUpdate(query);
where sent and title are variable strings extracted after applying some algorithm. But this gives sql error when sent or title contains single qoutes.
Consider using a prepared statement with parameters:
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO genes (sent, title) VALUES (?, ?)");
pstmt.setString(1, sent);
pstmt.setString(2, title);
pstmt.executeUpdate();
You should use PreparedStatement in fill the query parameters. It takes care of escaping the single quotes if any in the input parameters.
Modify your query and statement object as follows and it should be working:
String query = "INSERT INTO genes (sent, title) VALUES (? , ?)";
PreparedStatement pst = con.prepareStatement( query );
pst.setString( 1, sent );
pst.setString( 2, title );
int insertResult = pst.executeUpdate();
You should use PreparedStatements for that. PreparedStatement is under java.sql.* namespace.
String insertString = "INSERT INTO genes (sent, title) VALUES (?,?)";
// con is your active connection
PreparedStatement insertX = con.prepareStatement(updateString);
insertX.setString(1, sent);
insertX.setString(2, title);
insertX.executeUpdate();
You should never concatenate SQL statements like this, instead, use prepared statements:
String query = "INSERT INTO genes (sent, title) VALUES (?,?)";
PreparedStatement stmt = con.prepareStatement(query);
p.setString(1, sent);
p.setString(2, title);
p.executeUpdate();
If you use the string concatenation method you are exposing yourself to dangerous sql-injection attacks.
String query = "INSERT INTO genes (sent, title) VALUES (?, ?)";
PreparedStatement pt = con.prepareStatement(query);
pt.setString(1, sent);
pt.setString(2, title);
pt.executeUpdate();
Please, Remove ' from string or replace by \' from '.
Mysql allow only in \' format for special character.