Loading UUIDs from MySql database - java

i got a database where I use UUIDs as a primary key. I store the uuids as a binary(16) using java. To save an entry I use following
public boolean saveEntry(UUID id , String, name, int p1, int p2) throws SQLException
{
byte[] uuidBytes = new byte[16];
ByteBuffer.wrap(uuidBytes).order(ByteOrder.BIG_ENDIAN).putLong(id.getMostSignificantBits())
.putLong(id.getLeastSignificantBits());
String updateQuery = "INSERT INTO " + databaseTableName + " (ID, Name, p1, p2) "
+ "VALUES " + "(?, ?, ?, ?) "
PreparedStatement statement = null;
// write the id in the workflow table
statement = databaseConnection.prepareStatement(updateQuery);
statement.setBytes(1, uuidBytes);
statement.setString(2, name);
statement.setInt(3, p1);
statement.setInt(4, p2);
statement.execute();
This part is working and I can see my entries in the database.
However as soon as I try to load the entry with this:
public Workflow loadEntry(UUID id) throws SQLException
{
byte[] uuidBytes = new byte[16];
ByteBuffer.wrap(uuidBytes).order(ByteOrder.BIG_ENDIAN).putLong(id.getMostSignificantBits())
.putLong(id.getLeastSignificantBits());
String query = "SELECT " + "* " + "FROM " + databaseTableName + " WHERE " + databaseTableName
+ ".ID = ?";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try
{
preparedStatement = databaseConnection.prepareStatement(query);
preparedStatement.setBytes(1, uuidBytes);
resultSet = preparedStatement.executeQuery(query);
I get following mistake:
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'm not quite sure what the cause pf the error is. I know that using id.toString().replaceAll("-", "") works, but I'm not sure about perfomance and functionallity of this way. So is there any way I can get around this Solution?

Related

Insert int value of Resultset in SQL-Database

I'm working with a MySQL-Server and I'm trying to select an ID from another table and insert that ID in a table but it doesn't work all the time.
Code:
public void submit() throws Exception {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
Statement stmt1 = connection.createStatement();
ResultSet asset_id = stmt.executeQuery("SELECT id FROM cars.asset_type WHERE asset_type.name =" + "'" + sellables.getValue()+ "'");
while (asset_id.next()) {
System.out.println(asset_id.getInt("id"));
}
double value = parseDouble(purchased.getText());
System.out.println(value);
LocalDate localDate = purchased_at.getValue();
String insert = "INSERT INTO asset (type_id, purchase_price, purchased_at) VALUES ('"+ asset_id + "','" + value +"','" + localDate +"')";
stmt1.executeUpdate(insert);
}
I keep getting the same error message.
Caused by: java.sql.SQLException: Incorrect integer value: 'com.mysql.cj.jdbc.result.ResultSetImpl#1779d92' for column 'type_id' at row 1
There's no value in doing two client/server roundtrips in your case, so use a single statement instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
If you really want to insert only the last ID from your SELECT query (as you were iterating the SELECT result and throwing away all the other IDs), then use this query instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
ORDER BY id DESC -- I guess? Specify your preferred ordering here
LIMIT 1
Or with the JDBC code around it:
try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO asset (type_id, purchase_price, purchased_at) " +
"SELECT id, ?, ? " +
"FROM cars.asset_type " +
"WHERE asset_type.name = ?")) {
s.setDouble(1, parseDouble(purchased.getText()));
s.setDate(2, Date.valueOf(purchased_at.getValue()));
s.setString(3, sellables.getValue());
}
This is using a PreparedStatement, which will prevent SQL injection and syntax errors like the one you're getting. At this point, I really really recommend you read about these topics!

Java: Check the manual that corresponds to your MySQL server version for the right syntax to use near '?VALUES ('23')' at line 1

I am trying to update my database table but I have encountered a MySQLSyntaxErrorException. May I know how can I solve this error?
Thanks ! :)
//Retrieve data from database
String queryy = "SELECT agent.agentID, agent.agentEmail, departmentName FROM agent JOIN department ON agentEmail = email";
rs = myStat.executeQuery(queryy);
//Iterate the result set and get one row at a time
while (rs.next()) {
int id = rs.getInt("agentID");
email = rs.getString("agentEmail");
String emaill = email;
departmentName = rs.getString("departmentName");
String departmentNamee = departmentName;
System.out.println("Agent ID = " + id);
System.out.println("Department Name = " + departmentNamee);
System.out.println("Email = " + emaill + newLine);
//Update agentID in department table from agent table
String departmentUpdateSql = "UPDATE department SET agentID = ?"
+ "VALUES ('" + id +"')";
myStat.executeUpdate(departmentUpdateSql);'
And this is the error that I got:
Exception in thread "main" 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 ('23')' at line 1
sql update statements do not use the VALUES keyword (that is for inserts)
Use a PreparedStatement as below
String updateTableSQL = "UPDATE department SET agentID = ?"
PreparedStatement preparedStatement =
dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, id);
// execute update SQL stetement
preparedStatement.executeUpdate();
Note
I would imagine that you would also need some kind of where clause otherwise you will be updating all records

SQL in Prepared Statement throwing SQL exception

I'm trying to figure out why this code is throwing an SQL exception. When I run this code it prints "Bad SQL in customer insert ps", which is the message in that inner catch block. I've got multiple prepared statements with SQL inserts like this both in this class and also elsewhere in my application. They're all working fine. I've looked through this one over and over again, and I can't figure out why this one is throwing an exception.
try {
Connection conn = DBconnection.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";");
System.out.println(ps.toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customerId = rs.getString("customerId");
}
try {
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT "
+ "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)"
+ "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");");
customerInsert.executeUpdate();
System.out.println(customerInsert.toString());
System.out.println(rs.toString());
} catch (SQLException sq) {
System.out.println("Bad SQL in customer insert ps");
}
} catch (SQLException customerIdException) {
System.out.println("Bad SQL in customer ps");
}
You're using PreparedStatement as though you were using Statement. Don't put the parameters in the SQL, put in placeholder ? marks. Then use the various setXyz methods (setString, setInt, etc.) to fill in the parameters:
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
"INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(?, ?, ?, ?, ?, ?, ?);"
);
customerInsert.setString(1, name);
customerInsert.setInt(2, addressId);
// ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect

PreparedStatement troubles in Java [duplicate]

This question already has answers here:
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 7 years ago.
This is my method:
#Override
public void deleteOneRecord(String tableName, String id) throws ClassNotFoundException, SQLException{
// Validate the parameters here.
// String sql = "DELETE FROM " + tableName + " WHERE " + column + "=" + value;
String pKeyColumnName = "";
// Statement stmt = conn.createStatement();
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rs = dmd.getPrimaryKeys(null, null, tableName);
while(rs.next()){
pKeyColumnName = rs.getString("COLUMN_NAME");
System.out.println("PK column name is " + pKeyColumnName);
}
//String sql = "delete from " + tableName + " where " + pKeyColumnName + "=" + id;
String sql2 = "delete from ? where ?=?";
PreparedStatement pstmt = conn.prepareStatement(sql2);
pstmt.setString(1, tableName);
pstmt.setString(2, pKeyColumnName);
pstmt.setInt(3, Integer.parseInt(id));
pstmt.executeUpdate();
}
This is my test main:
public static void main(String[] args) throws ClassNotFoundException, SQLException {
DBStrategy db = new MySqlDBStrategy();
db.openConnection("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/book", "root", "admin");
System.out.println(db.findAllRecords("author", 0).toString());
db.deleteOneRecord("author", "2");
System.out.println(db.findAllRecords("author", 0).toString());
db.closeConnection();
}
The db object works, open connection works, my find all records method works,
then my deleteOneRecord blows up. I get this error:
Exception in thread "main" 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 ''author' where 'author_id'=2' at line 1
Now my syntax hasn't changed, I was running this code as just a Statement no problem a few minutes ago, so I must be using PreparedStatement incorrectly somehow.
Any help would be appreciated greatly.
I don't believe you can use parameters for the table name or the column name. You'll have to concatenate those into the string. Depending on where they come from, be careful about SQL injection vulnerabilities!

I need help selecting within a MySQL DateTime range in Java

I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception 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 '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.
Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...

Categories

Resources