I want to store six variables 3 are integers and three are of string data type, here is my prepared statement code
PreparedStatement stmt = connection.prepareStatement("insert into mydb (firstInt, firstString, secondString, secondInt, thirdInt, thirdString ) values (?, ?, ?, ?, ?, ?)");
stmt.setInt(1, firstInt);
stmt.setString(2, firstString);
stmt.setString(3, secondString);
stmt.setInt(4, secondInt);
stmt.setInt(5, thirdInt);
stmt.setString(6, thirdString);
stmt.executeUpdate();
The problem is string and integer type variables are not storing in database. What is wrong with this code?
May be you are not committing the transaction and autocommit might be set as false at database level. Please check your code and db settings.
Related
I want to insert 5 datas into one SQL table, the last four of which are already working and fine, but the first one should be from another table, a String, giving an Int to the table in which im inserting it. And this is my solution so far. However i'm still getting an error:
"The index 5 is out of range."
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1,1);
stmt.setInt(2, recid);
stmt.setInt(3, inputData);
stmt.setDate(4, sqlDate);
stmt.setTime(5, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
Actually you have only four parameters defined on your query, because LocationId is being calculated by the inner select you provided. That's why you are getting the error.
Try this:
PreparedStatement stmt = connection.prepareStatement("INSERT INTO RECORDS (LocationId, RecId, RecValues, YearTime, HourTime) VALUES " +
"((SELECT LocationId from Locations where Location_name = 'Mic HR1'), ?, ?, ?, ?)");
stmt.setInt(1, recid);
stmt.setInt(2, inputData);
stmt.setDate(3, sqlDate);
stmt.setTime(4, Time.valueOf(dtf.format(now)));
stmt.executeUpdate();
I'm having trouble inserting a row into a MySQL table with Java. I'm not sure what the problem is as it isn't giving an error. I'm trying to insert the row with the following:
String sql = "INSERT INTO users (uuid, authKey, code, scratches) VALUES (?, ?, ?, ?);";
PreparedStatement insertStmt = connection.prepareStatement(sql);
insertStmt.setString(1, uuid);
insertStmt.setString(2, key);
insertStmt.setInt(3, code);
insertStmt.setString(4, getScratchString());
insertStmt.executeUpdate();
The table 'users' is created successfully with no errors with the following:
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS users (uuid VARCHAR(40), authKey VARCHAR(30), code INT(10), scratches VARCHAR(45));");
When trying to insert the row with the same update in phpmyadmin, it works fine. There is no error given by the update so I have no idea where to start debugging. Any help would be appreciated. Thanks.
You have to do commit transaction check the below code
String sql = "INSERT INTO users (uuid, authKey, code, scratches) VALUES (?, ?, ?, ?)";
PreparedStatement insertStmt = connection.prepareStatement(sql);
insertStmt.setString(1, uuid);
insertStmt.setString(2, key);
insertStmt.setInt(3, code);
insertStmt.setString(4, getScratchString());
insertStmt.executeUpdate();
connection.commit();
I'm doing this:
String columns = "UserHash,EMail,Name,Gender,BirthYear,Birthday,MaritalStatus,UserID,ReferralUser,Likes";
String sql = "INSERT INTO Users ("+ columns+") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
byte[] bytesOfUserHash = user.getId().getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] userHash = md.digest(bytesOfUserHash);
stmt = con.prepareStatement(sql);
stmt.setBytes(1,userHash);
stmt.setString(2, user.getEmail());
stmt.setString(3, user.getName());
stmt.setInt(4, user.getGender().value());
stmt.setString(5, birthday.split("-")[0]);
stmt.setString(6, birthday);
stmt.setInt(7, user.getRelationshipStatus().value());
stmt.setString(8, user.getId());
stmt.setString(9, referraluser);
stmt.setString(10, likesjson);
stmt.executeUpdate();
All values are being inserted except for userHash, so the query is succeeding. What should I check?
Also, note I'm just hashing the userid right now, but I would like to hash the userid + CURRENT_TIMESTAMP.
UPDATE:
As a sanity check, I just tried tossing a string into the UserHash column as it is of type VARCHAR(45) and that's not working either. Something is obviously amiss independent of the MD5 issue.
You can use MySQL's built in MD5 function and only pass userId as parameter
String sql = "INSERT INTO Users ("+ columns+") VALUES (MD5(CONCAT(?,CURRENT_TIMESTAMP), ?, ?, ?, ?, ?, ?, ?, ?, ?);";
stmt = con.prepareStatement(sql);
stmt.setInt(1,user.getId());
...
I am learning MySQL with JAVA, and don't understand prepared statements. Abstracting from I shall learn it, I want to ask for help in finishing this code to be "prepared stated" :-)
String stringQuery = "INSERT INTO banlist (name, reason, admin, time, temptime, IP) VALUES (testNick, testPowod, testAdmin, CURRENT_TIMESTAMP, NOW(), NULL);=?";
PreparedStatement statement = this.connection.prepareStatement( stringQuery );
statement.setString( 1, ); // after ' 1, ' we define what we want to get
ResultSet resultSet = statement.executeUpdate();
String stringQuery =
"INSERT INTO banlist (name, reason, admin, time, temptime, IP)"
+ " VALUES (?, ?, ?, CURRENT_TIMESTAMP, NOW(), NULL)";
PreparedStatement statement = this.connection.prepareStatement(stringQuery);
statement.setString(1, testNick);
statement.setString(2, testPowod);
statement.setString(3, testAdmin);
int inserted = statement.executeUpdate();
Read the JDBC tutorial.
Here's how I'd do it:
String insertQuery = "INSERT INTO banlist(name, reason, admin, time, temptime, IP) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement statement = this.connection.prepareStatement( stringQuery );
statement.setString(1, name); // These values come from your code; dynamic
statement.setString(2, reason);
statement.setString(3, admin);
statement.setString(4, time);
statement.setString(5, tempTime);
statement.setString(6, ip);
int numRowsAffected = statement.executeUpdate();
Be sure to close your statement appropriately.
Hi I am trying insert data into the database using prepared statement but I am getting syntax error could u please help
public boolean SignUp(String last_name, String first_name,String email, String password,String confirm_password,String phone){
Connect connect = new Connect();
Connection conn = connect.Connection();
java.sql.PreparedStatement preparedStatement = null;
//NULL is the column for auto increment
String insertQuery = "INSERT INTO users VALUES (NULL, ?, ?, ?, ?, ?, ?)";
preparedStatement = conn.prepareStatement(insertQuery);
preparedStatement.setString(1, last_name);
preparedStatement.setString(2, first_name);
preparedStatement.setString(3, email);
preparedStatement.setString(4, password);
preparedStatement.setString(5, confirm_password);
preparedStatement.setString(6, phone);
int rs = preparedStatement.executeUpdate(insertQuery);
conn.close();
}
here is the error 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 '?, ?, ?, ?, ?, ?)' at line 1
I found the answer :)
Use preparedStatement.execute() instead of executeUpdate(sql). You have already set the sql and params - the new setting in executeUpdate(sql) overrides the bind.
You should change the statement to list the columns explicitly, and drop NULL from the list of values.
String insertQuery = "INSERT INTO users"
+ " (last_name, first_name, email, password, confirm_password, phone)"
+ " VALUES(?,?,?,?,?,?)";
This way your insert statement is no longer dependent on the order of columns in your users table, and is also immune to addition of columns to the table.
Note that although this design is probably OK for a toy or an education system, but in a real production system storing password in a table is very dangerous. Storing confirm_password is rather unusual, too: normally your system checks that password is the same as confirm_password, and then inserts a salted password hash and a salt into the table.
Just a guess, not I'm not certain. But if one of the fields is autoincrement, then I don't think you need to insert it. Try taking out that NULL....