What I currently have is this:
PreparedStatement ps = getSQLConnection().prepareStatement(
"REPLACE INTO " + table + " (uuid,name) VALUES(?,?)"
);
ps.setString(1, uuid.toString());
ps.setString(2, name.toLowerCase());
ps.executeUpdate();
However it is not setting only index 1 and 2, but instead clears the other column values. How can I insert into a row with only the first 2 indexes, and leave the other values untouched?
The table is created with this statement:
"CREATE TABLE IF NOT EXISTS data (" +
"`uuid` varchar(36) NOT NULL," +
"`name` varchar," +
"`owner` varchar," +
"`tags` varchar," +
"PRIMARY KEY (`uuid`));"
From the documentation:
REPLACE is a MySQL extension to the SQL standard. It either inserts, or deletes and inserts. For another MySQL extension to standard SQL—that either inserts or updates—see Section 13.2.5.3, “INSERT ... ON DUPLICATE KEY UPDATE Syntax”.
Related
INSERT OR REPLACE works when there is only one row in the table and it happens to be the one that is replaced. However, when there are multiple rows in the table, INSERT OR REPLACE just inserts and creates a duplicate!
For example, if I create an entry with eventId = '123'. And then try to write another entry with eventId = '123' and roomnumber equal to something different than the first entry, INSERT OR REPLACE will work. However, if there are more than one rows in the table it will create a duplicate. Here is my code:
String createSql = "CREATE TABLE IF NOT EXISTS events (\n"
+ " eventId VARCHAR(20) PRIMARY KEY ON CONFLICT REPLACE,\n"
+ " roomNumber VARCHAR(20) NOT NULL,\n"
+ " startTime TIMESTAMP NOT NULL,\n"
+ " endTime TIMESTAMP NOT NULL,\n"
+ " name VARCHAR(250),\n"
+ " isVIP BOOLEAN NOT NULL,\n"
+ " capacity INTEGER(20) NOT NULL, \n"
+ " UNIQUE (eventId) \n"
+ ");";
String sql = "INSERT OR REPLACE INTO events (eventId, roomNumber, startTime, endTime, capacity, name, isVIP)" + " Values('"+event.getID()+"', '"+event.getRoomNumber()+"', '"+event.getStartTime()+"', '"+event.getEndTime()+"', '"+event.getCapacity()+"', '"+event.getName()+"', '"+event.getVIPStatus()+"')";
I would read this thread for more information about how REPLACE works.
https://stackoverflow.com/questions/29539838/replace-versus-insert-in-sql#:~:text=According%20to%20the%20documentation%2C%20the,the%20new%20row%20is%20inserted.
Also I would suggest trying just "REPLACE," as it functions as INSERT but will replace on conflicts.
Here's the SQL I've tried so far to create the table
CREATE TABLE tblPosts (nId INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
strContent VARCHAR(140) NOT NULL,
strLink VARCHAR(200),
strImage VARCHAR(200));
using
String sql = "INSERT INTO tblPosts VALUES ('" + textFieldContent.getText() + "', '" +
textFieldLink.getText() + "', '" + textFieldImage.getText() + "')";
I get an error telling me I'm not providing the nId column value which I'm not but if the column auto-increments I'm not supposed to right?
I've also tried using the IDE to create the table on the database as described here
Alter a table column with auto increment by 1 in derby
Same response though. Any suggestions?
You need to include Start with 1, Increment by 1
Like this
CREATE TABLE tblPosts (nId INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY(Start with 1, Increment by 1),
strContent VARCHAR(140) NOT NULL,
strLink VARCHAR(200)
I would guess that since you're not specifying the column names in the SELECT, it is getting confused as to which columns the data should go in. I would specify the column names in your INSERT command.
You need to set THAT auto_increment column to DEFAULT like this:
String sql = "INSERT INTO tblPosts VALUES ( DEFAULT, '" + textFieldContent.getText() + "', '" +
textFieldLink.getText() + "', '" + textFieldImage.getText() + "')";
I am trying to add a new record to a table from Derby database. I need to use the record number in one of its fields. E.g. I need to save a path to the image in photo field. And the name of the image must corresponds its id. For example 1.jpg. I was trying this statement (file extention is not used in this example):
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Users (name, lastname, email, address, password, photo, lastvisit, status) VALUES ('" + name + "','" + lastname + "','" + email + "','" + address + "','" + DigestUtils.toMd5(password) + "', id, '" + now + "','user')");
But I get an error:java.sql.SQLSyntaxErrorException: Column 'ID' is either not in any table in the FROM list...
But this column definitely exists. What is the reason of the error?
Well the short answer imho is that you cannot do that in SQL.
In your table Users, I guess that your id column is an auto incremented primary key. What you can do is insert your record and then get the last id generated for this insert statement. Then you have to perform an update query to set the value of your photo column.
By the way, definitely learn to use placeholders in prepared statements
I'm not a specialist of Derby but browsing the doc I found how you can get the generated columns.
pstmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
int id = keys.getInt();
I'm trying to add a column to my table but I'm getting an error saying my syntax is wrong. I'm stuck, any ideas on correct syntax at line 2 on here?
String myColumnType = "DECIMAL";
st.executeUpdate("ALTER TABLE stocks.stockvalue ADD " + myColumnName + " " + myColumnType);
String updateTableSQL = ("UPDATE stocks.stockvalue SET stockvalue." + myColumnName + " = ? WHERE stockvalue.stockvalue_id = " + count);
PreparedStatement preparedStatement = conn.prepareStatement(updateTableSQL);
preparedStatement.setDouble(2, stockV);
preparedStatement.executeUpdate();
System.out.println("Done");
preparedStatement.close();
conn.close();
The syntax for adding column to existing table is
ALTER TABLE table_name
ADD column_name column-definition;
For example ,
"ALTER TABLE stockvalue ADD " + myColumnName + " " + myColumnType
I think you missed word TABLE in statement.
Try it. Hope this help you..
I'm trying to create a table similar to a ready table I created before (a template, if you will) where the only variable should be the table name.
This is what I've tried so far:
I exported the template table to mysql code and copied the code to a preparedStatement object as such:
createNewLineTableStatement = constantLink.prepareStatement("CREATE TABLE IF NOT EXISTS ? (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\");");
Than I try to execute the code by calling the following function:
private static boolean createNewLineTable(String tableName) throws SQLException{
createNewLineTableStatement.setString(1, tableName);
if (createNewLineTableStatement.executeUpdate() == Statement.EXECUTE_FAILED)
return false;
return true;
}
But I'm getting a syntax error exception:
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 ''line_37_var_1' ( `index` int(5) NOT NULL, `station` int(5) NOT NULL, PRIMARY' at line 1
How can I fix the code? OR is there a cleaner, better way to do the same thing? Maybe creating a script with a user variable? I thought of that but I've never used .sql script before.
Problem 1: You can't use a prepared statement parameter as the table name.
Problem 2: You have an unmatched paren and extra characters ");at the end of your statement.
Your query string should look something like:
String query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
by design, TableName and ColumnNames cannot be parameterized.
If you are scared about SQL Injection, create a custom function to check for malicious tableName. It is safe if the value comes inside of your application.
Then concatenate it in the string, add backtick for first level of defense :D
String tableName = "Your tableName";
String query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
You are missing Table name and i think that "?" shouldn't be there.
I will be something like
"CREATE TABLE IF NOT EXISTS YOURTABLE" + the following code