I'm trying to insert skeleton data into a database using jdbc.
So far my code is:
Statement st=con.createStatement();
String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
+ "VALUES (1, 1, 'forename1', 'surname1', '1996-06-03');";
I need to create 100 entries for this and I'm not too sure how to go about doing it.
All I want is the student id, titleid, forename and familyname to increment by 1 until it reaches 100 entries with those rows filled in, date of birth doesn't need to be altered. I'm asking how to do a loop for this
General answer - You should use PrepareStatement instead of Statement and execute as batch.
Common way to insert multiple entry or execute
String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
+ "VALUES (?, ?, ?, ?, ?);";
ps = connection.prepareStatement(SQL_INSERT);
for (int i = 0; i < entities.size(); i++) {
ps.setString(1, entity.get...());
...
ps.addBatch();
}
ps.executeBatch();
Important Note:
Why you should use PrepareStatement Over Statement
SQL Injection Example
There are two ways to do this. You can put your insert query inside a loop or you can put your loop inside an insert query. I have found that the better method depends on the database engine (but I've never used postresql) and the number of records you want to insert. You could bump up against the maximun query length or number of parameters or something.
The following code sample is ColdFusion, but it is intended to show the general idea of having a loop inside a query. You would have to write equivalent code in java.
<cfquery>
insert into yourtable
(field1
, field2
, etc)
select null
, null
, null
from SomeSmalllTable
where 1 = 2
<cfloop>
union
select <cfqueryparam value="#ValueForField1#">
, <cfqueryparam value="#ValueForField#">
, etc
</cfloop>
</cfquery>
Related
So i have two tables: locations and employees i want locations_id to be the same in employees.locations_id, I am trying to make it all in one statement
the erros is this 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 'INSERT INTO employees(employees_id, locations_id) VALUES('e1598','')' at line 1
String sql = " INSERT INTO locations( locations_id , username, password, id, type_of_id, first_name, last_name, phone, email, date_of_birth, address, sex ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
**Error here --->** + "INSERT INTO employees(employees_id,locations_id) VALUES (?,SELECT locations_id FROM locations INNER JOIN employees ON locations.locations_id =employees.locations_id)";
try {
MicroModelGUI micro = new MicroModelGUI();
PreparedStatement consulta = micro.connection.prepareStatement(sql);
consulta.setString(1, tflid.getText());
consulta.setString(2, tfuser.getText());
consulta.setString(3, tfpass.getText());
consulta.setString(4, tfid.getText());
consulta.setString(5, tftoid.getText());
consulta.setString(6, tffirst.getText());
consulta.setString(7,tflast.getText());
consulta.setString(8,tfphone.getText());
consulta.setString(9,tfemail.getText());
consulta.setString(10,tffdn.getText());
consulta.setString(11,tfaddress.getText());
consulta.setString(12,tfsex.getText());
consulta.setString(13,tfeid.getText());
int resultado = consulta.executeUpdate();
You should be using an INSERT INTO ... SELECT here:
INSERT INTO employees (employees_id, locations_id)
SELECT ?, l.locations_id
FROM locations l
INNER JOIN employees e ON l.locations_id = e.locations_id;
To the ? placeholder you would bind a value from your Java code. Note that while your version of SQL might support putting a scalar subquery into a VALUES clause, it is likely that your exact version would cause an error, as it would return more than one row.
This is my database:
dragons
id, key, name, age, creation_date
users
id, name, user, pass
users_dragons
user_id, dragon_id
So this is my code for deleting dragons from the database that have a bigger key that the passed and belongs to a determination user. The SQL query works perfectly for deleting them but not for returning the array of keys from the deleted elements.
I tried using PreparedStatement but later I checked, as far as I know, that this class doesn't return arrays, and the CallableStatement is only for executing processes in the db, and I don't know how they return arrays.
String query = "" +
"DELETE FROM dragons " +
"WHERE id IN (SELECT d.id FROM dragons d, users u, users_dragons ud" +
" WHERE d.key > ?" +
" AND ud.dragon_id = d.iD" +
" AND ud.user_id in (select id from users where id = ?)) RETURNING key INTO ?";
CallableStatement callableStatement = connection.prepareCall(query);
int pointer = 0;
callableStatement.setInt(++pointer, key);
callableStatement.setInt(++pointer, credentials.id);
callableStatement.registerOutParameter(++pointer, Types.INTEGER);
callableStatement.executeUpdate();
return (int []) callableStatement.getArray(1).getArray();
The code is giving me the error, but is obvious because the CallableStatement needs a postgres function to run and not a simple SQL query
org.postgresql.util.PSQLException: This statement does not declare an OUT parameter.
Use { ?= call ... } to declare one.
at org.postgresql.jdbc.PgCallableStatement.registerOutParameter
.......
It would be really helpful how would be the correct JDBC algorithm to delete the elements from the database and return the array of keys of the deleted items.
You treat such a statement like a normal SELECT statement: use java.sql.PreparedStatement.executeQuery() or java.sql.Statement.executeQuery(String sql) to execute the statement and get a result set.
java.sql.CallableStatement is for calling Procedures (but you don't need it in PostgreSQL).
This is my first post here, if my formatting is not correct/ hard to read, I will change it. Please let me know.
I have been playing with JDBC trying to add basic data to a database, using user input data. The user provides first and last name, email, and a user id is generated using the random function.
The database was created using postgreSQL. I'm trying to add to a table called accounts, which contains the following columns - user_id (integer), first_name (varchar(100)), last_name (varchar(100)), email (varchar(500)).
My program is able to connect to the database successfully, but it's not able to add data to the table.
in the following code, firstName, lastName, and eMail are all strings, while sID is an int.
state = conx.prepareStatement("INSERT INTO accounts VALUES ("+ sID +","+ firstName + "," + lastName + "," + eMail) + ")");
s.executeUpdate();
Normally, I'd hope the data would be added to the table so we can call it a day, but I'm getting an error.
org.postgresql.util.PSQLException: ERROR: column "v" does not exist
Position: 36
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:120)
at Main.main(Main.java:49)
org.postgresql.util.PSQLException: ERROR: column "v" does not exist
Position: 36
Use ? for parameters instead of concatenating their values. Also, you should name the columns in the INSERT statement. For example:
s = conx.prepareStatement(
"INSERT INTO accounts (id, first_name, last_name, email) " +
"VALUES (?, ?, ?, ?)"
);
s.setInt(1, sID);
s.setString(2, firstName);
s.setString(3, lastName);
s.setString(4, email);
int affectedRows = s.executeUpdate();
This question already has answers here:
Invalid column index using PreparedStatement
(2 answers)
Closed 4 years ago.
In JDBC with Oracle DB, I want to retrieve Employees whose first name starts with a specific letter. How can I use parameter marker "?" in a like condition? setXXX() method doesn't see it when i place it in a single quotation.
ex:
PreparedStatement ps = null;
String sql="SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE FIRST_NAME like '?%'";
ps = conn.prepareStatement(sql);
ps.setString(1, firstName);
Concatenate the bound value with the wildcard:
"SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE FIRST_NAME like ? || '%'"
You could also check the first letter explicitly with something like:
"SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE SUBSTR(FIRST_NAME, 1, 1) = ?"
but that may be less efficient (unless you add a function-based index).
The normal route is to set the % in the 'setX' call, so your query becomes SELECT FIRST_NAME, LAST_NAME, SALARY FROM EMPLOYEES WHERE FIRST_NAME like ? and then .setString(1, firstChar + "%");
The alternative is as #Alex Poole answered: use WHERE FIRST_NAME like (? || '%')
NB: This answer was edited: The query included an erroneous % at the end; it has been removed.
This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 9 years ago.
I am using a java PreparedStatment object to construct a series of batched INSERT queries. The query statement is of the format...
String strQuery = "INSERT INTO ? (col1, col2, col3, col4, col5) VALUES (?,?,?,?,?,?);";
...so both field values and the tablename are variables (ie. I have multiple tables with the same column format of which each insert will be directed to a different one). I can get the executes to work if I remove the "?" tablename variable and hard code but each prepared statement will be inserted into a different table so needs to remain a variable I populate immediately prior to executing the batch query using...
stmt.setString(1, "tableName1");
How can I let this be a dynamic variable please?
You can't. You need to contruct the sql with string concatenation/placeholder with String.format. prepared statement is for the column values not for table name.
You can use placeholder in place of table name and then replacing that with your tablename.
String strQuery = "INSERT INTO $tableName (col1, col2, col3, col4, col5)
VALUES (?,?,?,?,?,?);";
and replace when u come to know the tablename
String query =strQuery.replace("$tableName",tableName);
stmt =conn.prepareStatement(query);
One alternative could be String.format:
e.g.
String sql = String.format("INSERT INTO $1%s (col1, col2, col3, (etc)", myTablename);
If your table name is coming from your own code ONLY...
...you would need to add it to the original string:
String tableName = "some_table_name";
// some other code
String strQuery = "INSERT INTO " + tableName + " (col1, col2, col3, col4, col5) VALUES (?,?,?,?,?,?);";
If the table name is coming any other unreliable source (user input, a parameter that other code is passing in), do not do this and see the other answers!