I am currently working on a program the function of which is to store my passwords, and this is why I am using an SQL database called Users. This database contains tables for all the users which will be using the program. Those tables have four columns:
SiteName, Username, Password, AdditionalInfo
I am having a problem updating a specific row. This is my the code I get an error with:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
c.setAutoCommit(false);
stmt = c.createStatement();
String update = "UPDATE " + user + " set Username = " + usernamej + " where SiteName = " + siteEdited;
stmt.executeUpdate(update);
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
It is in a class made specifically for dealing with the sql database and it gets the following error when I try to change the username to 'test':
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such column: test)
Assuming the value you pass in for user is the name of the table, your update string is going to look like
UPDATE usertable SET Username = test where SiteName = siteEditedValue
You need to quote the string values:
UPDATE usertable SET Username = 'test' where SiteName = 'siteEditedValue'
The quick and dirty way is:
String update = "UPDATE " + user + " set Username = '" + usernamej + "' where SiteName = '" + siteEdited + "'";
However, it's much (much, much) better to use a PreparedStatement in this case:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
stmt = c.prepareStatement("UPDATE " + user + " SET Username = ? Where SiteName = ?");
stmt.setString(1, usernamej);
stmt.setString(2, siteEdited);
stmt.executeUpdate();
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
This code assumes the type of stmt is PreparedStatement, not just Statement.
As well as taking care of quoting the values for you, this will escape any sql for you, preventing the possibility of SQL-injection attacks (while these are far less of an issue in a desktop application that a web application, it's still a good habit to get into).
#griFlo I got it running with this code:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
c.setAutoCommit(false);
PreparedStatement stmt = c.prepareStatement("UPDATE " + user + " SET Username = ? Where SiteName = ?");
stmt.setString(1, usernamej);
stmt.setString(2, siteEdited);
stmt.executeUpdate(update);
c.commit();
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
I had forgotten to put c.commit();
Related
see the screenshots
see the 2nd screenshot
see the 3rd screenshot
Okay so I am building a project on java and mysql, I am stuck at this point that I have to update a data which is in MySql but from my java gui application, I've executed that update command from MySql command line client
update user set bldu = 50 where userid = 1001;
and it's working perfectly fine there but from my java application on clicking on assigned jbutton it says:
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 'userid= 1001' at line 1
Please help me..!
In your first screenshot you must add a space before WHERE clause:
String query = "UPDATE user SET bdlu = " + bldut + "WHERE userid = " + uid + ";";
So your query will be interpretated as:
UPDATE user SET bdlu = 50WHERE userid = 1001
So you'll raise a syntax error.
Then you'll have the following query:
String query = "UPDATE user SET bdlu = " + bldut + " WHERE userid = " + uid + ";";
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
use this one instead of your old query may be it is helpful for you.
Try this snippet in your code.
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
Statement = con.prepareStatement(query);
Statement.executeUpdate();
by looking at your code you cannot store results of update query in resultSet the executeUpdate() only return 0 or 1 for success and failure of Update.
Okay i guys i have figured out something that it is working i mean this program is updating the data stored in mysql from netbeans via jdbc but it won't stop showing that error message like:
"Can not issue data manipulation statements with executeQuery()"
everytime i click one that assigned jButton..! but i checked the database the value i want to change is being changed but then why it is showing this error..?
Please use this code in your java file, do changes according to your file. your issue is you are using the same query in a result set that already uses for the update
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bdb", "root", "root");
try {
String query = "update user SET bldu = " + bldut+ " WHERE userid = " + uid + ";";
// create the java mysql update preparedstatement
Class.forName("com.mysql.jdbc.Driver").newInstance();
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.executeUpdate();
query = "select * from user WHERE userid = " + uid +";";
ResultSet rs = stmt.executeQuery(query);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String userid = rs.getString("userid");
String userfname = rs.getString("userfname");
// all your column
// Display values
System.out.print("userid: " + userid);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
} finally {
// finally block used to close resources
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try
I'm coding some database transactions by using java. I'm sending a query using java. I think it has no problem with it. And if I send the query at prompt, it is working.
This method is updating book quantity.
private static void updateBquantity(int bqt, String bname) {
Connection con = makeConnection();
try {
Statement stmt = con.createStatement();
System.out.println(bqt + " " +bname);
//this part is making problem
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where bookname = '" + bname + "';");
System.out.println("<book quantity updated>");
} catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where 도서이름 = '" + bname + "';");
This part is making problem.
Other queries using this form is working.
The compiler says :
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 'bookname = 'Davinci Code'' at line 1
Help me.
I'm confused with bookname = 'Davinci Code, where is bookname in your query? No matter what, in this query, you missed a blank before where, try this:
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + " where 도서이름 = '" + bname + "';");
I was trying to make a register program in Java in Eclipse.
But i got an error :
java.sql.SQLException: Query does not return results
You can see my following code :
Login.addnewuser(lblname.getText(), lblusername.getText(), lblpseudo.getText(), passwordField.getText(), rankchoice.getSelectedItem());
of :
public static void addnewuser(String Name, String Username, String Pseudo, String Password, String Rank) {
String query = ("INSERT INTO UsersInfos (Name, Username, Pseudo, Password, Rank) " + "VALUES ('" + Name + "' , '" + Username + "' , '" + Pseudo + "' , '" + Password + "' , '" + Rank + "')");
connection = SqliteConnection.dbConnector();
try {
PreparedStatement name2 = connection.prepareStatement(query);
name2.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
Can someone help me please ? Thanks :) !
For INSERT, UPDATE or DELETE use the executeUpdate() method and for SELECT use the executeQuery() method which returns the ResultSet.
I'm trying to check if the "Username" and "Email" arguments in my constructor are existed in the SQL Table.
this is my code:
public DB(String usr, String eml, String pwd) {
this.usr = usr;
this.eml = eml;
this.pwd = pwd;
String jdbcUrl = "jdbc:mysql://localhost:3306/registered";
String jdbcUser = "....";
String jdbcPassword = "....";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);
statement = connection.createStatement();
now , if i use SELECT with two columns, like this:
String command = "SELECT UserName,Email FROM users WHERE UserName LIKE '" + this.usr.toString() + "';";
resultSet = statement.executeQuery(command);
and then do my loop for resultSet... like this:
while (resultSet.next()) {
if (usr.equalsIgnoreCase(resultSet.getString("UserName"))) {
System.out.println("UserName : " + this.usr + " is taken!");
}
else if (eml.equalsIgnoreCase(resultSet.getString("Email"))) {
System.out.println("Email : " + this.eml + " is taken!");
}
else {
System.out.println("Email : " + this.eml + " and UserName : " + this.usr + " are AVAILABLE!");
command = "INSERT users SET UserName = '" + this.usr.toString() + "',Email = '" + this.eml.toString() + "',Password = '" + this.pwd.toString() + "',Status = '0' ,Connected = '1';";
statement.executeUpdate(command);
}
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("Vendor error: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
the
resultSet.next()
only runs over the "FIRST" column which means
if the "usr" exists in the table it works,
but if the "usr" does not exist in the table, the other two if statements does-not work ..
,... i want to check both first column and second,.. and maybe third or more soon.. , any help?
Your WHERE clause only tests for the UserName, so if the UserName doesn't match this.usr.toString(), the resultSet will be empty, so the while loop won't be entered.
You should change the query to match all the fields you care about - something like - "SELECT UserName,Email FROM users WHERE UserName = ... OR Email = ..."
If the resultSet is empty, you'll know that you can insert the new record. Otherwise, you can check which of the fields (UserName, Email) is already taken.
One more thing you should be aware of - executing a SQL statement without PreparedStatement makes your code vulnerable to SQL injection attacks.
You should change your code to something like this :
PreparedStatement pstmt = con.prepareStatement("SELECT UserName,Email FROM users WHERE UserName = ? OR Email = ?");
pstmt.setString(1, this.usr);
pstmt.setString(2, this.eml);
resultSet = pstmt.executeQuery();
You should change your INSERT statement similarly to use PreparedStatement.
Good evening.
I am doing a basic exercise to insert data into an Access Database Table and in the code lies a syntax error which I am struggling to pinpoint.
Was hoping could receive some help with that as to where that Syntax problem lies.
The error reads as follow
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same.
public void addData(String ID, String name, String address, String type) throws SQLException
{
int rowsadded;
Statement statement = conn.createStatement();
String queryString = "INSERT INTO Artists(ID, Name, Address, Type) VALUES (" + ID + ", '" + name + "', '" + address + ", " + type + "')";
System.out.println(queryString);
System.out.println(ID + "(ID) added to the database");
rowsadded = statement.executeUpdate(queryString);
System.out.println("Rows updated = " + rowsadded);
}
Method call happens as follow
Insertingdata example;
try
{
example = new Insertingdata();
example.addData("15", "Bob Dylan", "Los Angeles", "Folk");
}
catch(SQLException se)
{
se.printStackTrace();
}
catch(ClassNotFoundException ce)
{
ce.printStackTrace();
}
You missed a couple of single quotes in the query, so address and type were being read as a single value. Replace your queryString line with:
String queryString = "INSERT INTO Artists(ID, Name, Address, Type) VALUES (" + ID + ", '" + name + "', '" + address + "', '" + type + "')";
This should fix the problem.