java sql insert preparedstatment error - java

String sql = " INSERT INTO `tblservice` (`ServiceID`,`accountID`, `Kind`, `Description`, `Price`, "
+ "`Quantity`, `Total`, `DateAndTime`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setInt(1, this.accountID);
pstm.setString(2, "" + SelectionBox.getSelectedItem());
pstm.setString(3, desc);
pstm.setFloat(4, Float.parseFloat(PriceTF.getText()));
pstm.setFloat(5, Float.parseFloat(QuantityTF.getText()));
pstm.setFloat(6, this.getTotal());
pstm.setDate(7, dateAdded);
pstm.executeUpdate();
Error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '?, ?, ?, ?, ?, ?, ?)' at line 1

Instead of make NULL in your query VALUES (NULL, ...) use setNull for example :
pstm.setNull(1, java.sql.Types.INTEGER);
It will take the type, of your field, in this example i consider it is a java.sql.Types.INTEGER it can be java.sql.Types.VARCHAR or any sql type
So your query should be like this :
String sql = "INSERT INTO tblservice (ServiceID, accountID, Kind, Description,
Price, Quantity, Total, DateAndTime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setNull(1, java.sql.Types.INTEGER);
pstm.setInt(2, this.accountID);
....

Related

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

I've researched this error, and it seems like it comes from mere mistakes on behalf of the SQL command. My command looks right to me, but maybe I'm missing something. My full 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 'VALUES ('John', 'Doe', '12/19/91', 'N/A', 'Single', 'N/A', 'N/A', 'N/A', '12/10/' at line 1
Now my code snippet, any help is greatly appreciated:
String DML = "INSERT INTO MEMBERS (FIRST_NAME, LAST_NAME, BIRTHDATE, DEATH_DATE, MARITAL_STATUS, WEDDING_DATE, SPOUSE_NAME, MILITARY_SERVICE, DATE_JOINED, DEPARTURE_DATE, ACCEPTANCE_MODE, DEPARTURE_MODE, RELATED_TO, NOTES VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(DML);
pstmt.setString(1, jTextField2.getText());
pstmt.setString(2, jTextField1.getText());
pstmt.setString(3, jTextField6.getText());
pstmt.setString(4, jTextField11.getText());
pstmt.setString(5, jTextField3.getText());
pstmt.setString(6, jTextField5.getText());
pstmt.setString(7, jTextField4.getText());
pstmt.setString(8, jTextField8.getText());
pstmt.setString(9, jTextField7.getText());
pstmt.setString(10, jTextField10.getText());
pstmt.setString(11, jTextField9.getText());
pstmt.setString(12, jTextField13.getText());
pstmt.setString(13, jTextField14.getText());
pstmt.setString(14, jTextArea1.getText());
pstmt.executeUpdate();
Missing ) between NOTES) VALUES
INSERT INTO MEMBERS (FIRST_NAME, LAST_NAME, BIRTHDATE, DEATH_DATE, MARITAL_STATUS, WEDDING_DATE, SPOUSE_NAME, MILITARY_SERVICE, DATE_JOINED, DEPARTURE_DATE, ACCEPTANCE_MODE, DEPARTURE_MODE, RELATED_TO, NOTES) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

PreparedStatement - syntax error

I have a problem with PreparedStatement.
This is my function that adds new user to MySQL database:
public static void createUser(String fn, String sn, String log, String pass, int accNum, String qst, String answ) {
try {
Connection conn = (Connection) mySQLConnector.getConnection();
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(
"INSERT INTO users"
+ "(FirstName, LastName, Login, Password, AccountNumber, Ballance, Question, Answer)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?");
ps.setString(1, fn);
ps.setString(2, sn);
ps.setString(3, log);
ps.setString(4, pass);
ps.setInt(5, accNum);
ps.setDouble(6, 0);
ps.setString(7, qst);
ps.setString(8, answ);
ps.executeUpdate();
ps.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
And this is an error that I get:
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 have no idea what is wrong with my query. ColumnNames are ok, function arguments are also ok.
I've tried adding '' to columns names (like that: 'FirstName') but i t still doesn't work...
EDIT:
Adding spaces did not helped.I even made it in one line:
"INSERT INTO users (FirstName, LastName, Login, Password,
AccountNumber, Ballance, Question, Answer) VALUES (?, ?, ?, ?, ?, ?,
?, ?)"
and still gives the same error
You are missing spaces. Change your SQL to :
"INSERT INTO users " // space added
+ "(FirstName, LastName, Login, Password, AccountNumber, Ballance, Question, Answer) " // space added
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
EDIT : I missed the missing closing bracket at the end of the VALUES clause.
I think you just need to add spaces and bracket
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(
"INSERT INTO users "
+ "(FirstName, LastName, Login, Password, AccountNumber, Ballance, Question, Answer) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
Fix this:
"VALUES (?, ?, ?, ?, ?, ?, ?, ?");
to this:
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

How can I insert a String of base64-encoded data into an sqlite3 table?

I am writing an android app. I have an String of base64-encoded data, and I want to store it in my sqlite3 table. I am trying to do the following:
SQLiteDatabase db = new MyDatabase(MyApplication.getContext()).getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("insert into MyTable values($next_id, ?, ?, ?, ?, ?, ?);");
stmt.bindLong(1, id);
stmt.bindString(2, someString);
stmt.bindLong(3, someLong);
stmt.bindLong(4, anotherLong);
stmt.bindLong(5, moreLong);
stmt.bindString(6, base64Data); // the field in question
stmt.execute();
But I get this error:
(1299) abort at 19 in [insert into MyTable values($next_id, ?, ?, ?, ?, ?, ?);]: NOT NULL constraint failed: MyTable.base64Data
MyTable.base64Data schema is: base64Data text NOT NULL
I can see in my debugger that base64Data is not null, so I think my query must not be formed correctly.
I also tried putting the last question mark in quotes:
SQLiteStatement stmt = db.compileStatement("insert into MyTable values($next_id, ?, ?, ?, ?, ?, \"?\");");
But that did not fix the error. What do I need to do?
You have seven parameters, but bind only six.
(If the first column should be autoincrementing, use NULL instead of $next_id.)

SQL 1064 Syntax Error using a JDBC prepared statement

I have:
String query = "INSERT INTO Basestations VALUES(?, ?, ?, ?, ?, ?, ?,"
+ "?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement prep = conn.prepareStatement(query);
prep.setInt(1, profile.getNetworkId());
prep.setInt(2, profile.getBaseStationId());
prep.setInt(8, profile.getLoadLevel());
prep.setInt(11, profile.getPositionX());
prep.setInt(12, profile.getPositionY());
prep.setInt(13, profile.getPort());
prep.setDouble(3, profile.getSignalStrength());
prep.setDouble(4, profile.getFrequency());
prep.setDouble(6, profile.getMaxBitrate());
prep.setDouble(7, profile.getGuaranteedBitrate());
prep.setDouble(10, profile.getRange());
prep.setString(5, profile.getNetworkType());
prep.setString(9, profile.getProvider());
prep.setString(14, profile.getCharging());
prep.setBoolean(15, true);
prep.executeUpdate(query);
and i am getting:
INFO: SQL Exception:
INFO: State : 42000
INFO: Message: 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
INFO: Error : 1064
what could be wrong?
You're passing an string representing an invalid SQL statement to the executeUpdate() method when you don't need to. Try just doing prep.executeUpdate();.
In your last line you don't need pass the variable query.
So change
prep.executeUpdate(query);
For:
prep.executeUpdate();
The main error is here:
// incorrect
prep.executeUpdate(query);
// correct
prep.executeUpdate();
But please try to put your SQL in the following form:
UPDATE table_name(field1, field2, field3) VALUES(?, ? ,?)
This will prevent your code from breaking if there is an update to the table.

SQLException - Generated keys not requested (MySQL)

I get this error when im making a new character to my game, in the CreateCharHandler it sends "saveToDb(false);" but when im ingame with another char i manually created i can saveToDb(true); with no error. please help, why is this happening?
http://i56.tinypic.com/oh1pn5.png
SaveToDb method http://pastebin.com/9sT5XBxp
line 3514 is:
ResultSet rs = ps.getGeneratedKeys();
Thanks in advance!
Your SQLException clearly states that:
You need to specify Statement.RETURN_GENERATED_KEYS to the
Statement.executeUpdate() or Connection.prepareStatement().
This can be achieved as follows (adding an additional value on Connection.prepareStatement() method):
String SQL = ""; //whatever my String is
PreparedStatement ps = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "value");
//Other necessary ps.setXXX() methods
//now update
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
The Statement.RETURN_GENERATED_KEYS is key here.
Hope this helps!
PS: Useful resource.
#Charlie berg, since you prefer being lazy, I changed line 13 of your code to include the Statement.RETURN_GENERATED_KEYS:
ps = con.prepareStatement("INSERT INTO characters (level, fame, str, dex, luk, `int`, exp, hp, mp, maxhp, maxmp, sp, ap, gm, skincolor, gender, job, hair, face, map, meso, hpMpUsed, spawnpoint, party, buddyCapacity, messengerid, messengerposition, mountlevel, mounttiredness, mountexp, equipslots, useslots, setupslots, etcslots, monsterbookcover, watchedcygnusintro, vanquisherStage, dojopoints, lastDojoStage, finishedDojoTutorial, vanquisherKills, matchcardwins, matchcardlosses, matchcardties, omokwins, omoklosses, omokties, givenRiceCakes, partyquestitems, jailtime, accountid, name, world) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
Also, Statement class is of package java.sql (make sure you import correctly). :-)
Oracle Documents:
If there is no indication that auto-generated columns should be made
available for retrieval, a call to Statement.getGeneratedKeys will
return a null ResultSet.
You should explicitly tell to JDBC That you want generated keys.
like this:
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
or
conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
and then you can use getGeneratedKeys().

Categories

Resources