I want to use insert statement with select subquery from another table. In my case, I want to add a row from PRESENTATION table to AVAILABILITY table.
AVAILABILITY table structure:
availableID (number, generated using sequence)
availableDay (varchar)
availableStart (varchar)
availableEnd (varchar)
lecturerID(FK) (varchar)
presentationID(FK) (number, generated using sequence)
PRESENTATION table structure:
presentationID (number, generated using sequence)
presentationDay (varchar)
presentationStart (varchar)
presentationEnd (varchar)
I tried to construct the query in DAO like this :
String lecturerID = Abean.getLecturerID();
String availableDay = Abean.getAvailableDay();
String availableStart = Abean.getAvailableStart();
String availableEnd = Abean.getAvailableEnd();
Date availableDate = Abean.getAvailableDate();
String presentationID = Abean.getPresentationID();
try{
currentCon = JavaConnectionDB.getConnection();
PreparedStatement ps=currentCon.prepareStatement("
insert into availability (availableID,
lecturerID,
availableDay,
availableStart,
availableEnd,
presentationid)
select(availabilityseq.nextval,
?,
presentationDay,
presentationStart,
presentationEnd,
presentationid)
from presentation where presentationid=?
");
ps.setString(1,Abean.getLecturerID());
ps.setString(2,Abean.getAvailableDay());
ps.setString(3,Abean.getAvailableStart());
ps.setString(4,Abean.getAvailableEnd());
ps.setString(5,Abean.getPresentationID());
// ps.setString(6,Abean.getAvailableID());
ps.executeUpdate();
}
catch(Exception e){
System.out.println("add availability 2 failed: An Exception has occurred! " + e);
}
As expected, it return error
ERROR: java.sql.SQLException: Invalid column index
So, how can i do insert with subquery with extra column?
UPDATE: MY DAO codes
You need to match the setting of bind variables values with the bind variables specification in the SQL text :
EDIT Apr 18th: removed parenthesis from select subquery
PreparedStatement ps=currentCon.prepareStatement("
insert into availability (availableID,
lecturerID,
availableDay,
availableStart,
availableEnd,
presentationid)
select availabilityseq.nextval,
?,
presentationDay,
presentationStart,
presentationEnd,
presentationid
from presentation where presentationid=?
");
ps.setString(1,Abean.getLecturerID()); // match first "?"
ps.setString(2,Abean.getPresentationID()); // match 2nd "?"
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.
I am created a prepared select query and it appears the query is not picking up the DESC or I have the bind_param structured wrong. I am trying to get the last id of the user_id's image to display. The user's image displays, but it is the first id image they have. I tried doing ASC and it was the same thing.
Am I doing this right?
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY ? DESC LIMIT 1
";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("ss", $user_id, `id`);
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$stmt->bind_result($id, $user_id, $profilePic);
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
echo '<img id="home-profile-pic" src=" '.$profilePic.'">';
}
I don't think you can :
Use placeholders in an order by clause
Bind column names : you can only bind values -- or variables, and
have their value injected in the prepared statement.
You can use number instead of field name in the 'order by' clause
Why you have put ? after "order by" statement?
Your order by should reference to either id of your "profile_img" table or any timestamp field in that table...
e.g. $sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC LIMIT 1
";
here replace id (i am assuming this name) with the primary key field name of profile_image table
or
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY created_on DESC LIMIT 1
";
here created_on (which i have also assumed) can be replaced by any timestamp field if you any in profile_img table
I am trying to execute a create query using JDBC. I have a method which creates the query and then I execute it but its showing me syntax error. Below is the stack trace :
com.mysql.jdbc.exceptions.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 'supplierId varchar,supplierUrl varchar,totalActivities varchar,activityName varc' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3243)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1343)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1260)
Now the query generated is this :
create table demo ( ID INTEGER PRIMARY KEY AUTO_INCREMENT,supplierName varchar,supplierId varchar,supplierUrl varchar,totalActivities varchar,activityName varchar,activityPrice varchar,tourCode varchar,starRating varchar,totalReviews varchar,geography varchar,duration varchar,category varchar,subCategory varchar);
And below is the method which is generating this query :
private static String getCreateTableQuery(String tableName, String columnData) {
StringBuilder sqlStatement = new StringBuilder("");
sqlStatement.append("create table " + tableName + " ( ID INTEGER PRIMARY KEY AUTO_INCREMENT,");
String[] columns = columnData.split(">"); // columns are separated by >
for (int i = 0; i < columns.length; i++) {
sqlStatement.append(columns[i] + " varchar");
if (i != columns.length - 1) { // no commas after last column
sqlStatement.append(",");
}
}
sqlStatement.append(");");
return sqlStatement.toString();
}
And this is how am executing the query :
SessionImpl sessionImpl = (SessionImpl) getSessionFactory().openSession();
Connection conn = (Connection) sessionImpl.connection();
Statement statement = (Statement) conn.createStatement();
statement.executeUpdate(query);
sessionImpl.close();
conn.close();
Am unable to understand the syntax error. Can someone please explain?
I think you have to pass max length for varchar fields:
Please check this your query will be like that:
create table demo ( ID INTEGER PRIMARY KEY AUTO_INCREMENT,supplierName varchar(255),supplierId varchar(255),supplierUrl varchar(255),totalActivities varchar(255),activityName varchar(255),activityPrice varchar(255),tourCode varchar(255),starRating varchar(255),totalReviews varchar(255),geography varchar(255),duration varchar(255),category varchar(255),subCategory varchar(255));
Here is insert Query:
insert into demo
( supplierName, supplierId, supplierUrl, totalActivities, activityName,
activityPrice, tourCode, starRating, totalReviews, geography, duration,
category, subCategory)
values
(supplierName, supplierId, supplierUrl, totalActivities, activityName,
activityPrice, tourCode, starRating, totalReviews, geography, duration,
category, subCategory)
In Mysql you need to define a length to the varchar. Take a look here:
Why does VARCHAR need length specification?
I don't see a problem with your Java code. Fix your create table statement and you'll probably be fine.
In PostgreSQL user is a reserved keyword that is used in an internal table, however I also have a separate user table in my own database that I need to use. Whenever I try to execute INSERT or UPDATE statements on the table, it generates the following error: The column name 'id' was not found in this ResultSet.
This is the Java code I am currently using:
PreparedStatement stat1 = conn.prepareStatement("SELECT id FROM user;");
PreparedStatement stat2 = conn.prepareStatement("UPDATE user SET date_created = ? , last_updated = ? , uuid = ? WHERE id = ?;");
ResultSet rs = stat1.executeQuery();
while(rs.next()){
UUID uuid = UUID.randomUUID();
String tempId = uuid.toString();
stat2.setTimestamp(1, curDate);
stat2.setTimestamp(2, curDate);
stat2.setString(3, tempId);
stat2.setLong(4,rs.getLong("id"));
stat2.executeUpdate();
}
So my question is, how could I insert or update the values in my personal user table without interfering with the keyword restriction?
Use this:
prepareStatement("UPDATE \"user\" set date_created = ?")
Or, better yet, rename your user table to something else, like users:
ALTER TABLE "user" RENAME TO users;
Escape the table name like this
select * from "user";
I have this piece of code, with a prepared statement. I know the query is redundant. the parameter id is a string <space>413530 (" 413530"). Please note the preceding whitespace character.
String query = "SELECT RSCode as id FROM Customer WHERE RSCode=?";
PreparedStatement newPrepStatement = connection
.prepareStatement(query);
newPrepStatement.setString(1, id);
resultSet1 = newPrepStatement.executeQuery();
while (resultSet1.next()) {
System.out.println("Got a result set.");
logindata.add(resultSet1.getString("id"));
}
I do not get any results after executing this query.
Now, if I use the same statements and append the parameter as part of the string as follows:
String query = "SELECT RSCode as id FROM Customer WHERE RSCode=" + id;
PreparedStatement newPrepStatement = connection
.prepareStatement(query);
resultSet1 = newPrepStatement.executeQuery();
while (resultSet1.next()) {
System.out.println("Got a result set.");
logindata.add(resultSet1.getString("id"));
}
I get a result as after executing this prepared statement. Same also works with a java.sql.statement
I wish to know why the driver ignores the whitespace in the second piece of code, but has a problem in the first part.
If you use setString the parameter will be bound as a string resulting in this SQL (considering the bound parameter an SQL string):
SELECT RSCode as id FROM Customer WHERE RSCode=' 0123';
If you use concatenation the SQL used will be (considering the concatenated value as an integer, since space will be ignored as part of the SQL syntax):
SELECT RSCode as id FROM Customer WHERE RSCode=<space>0123;
In this case I would advise to convert it to int or long or whatever it is and bind it with the right type. With setInt() or setLong().
And if you field is a string you could normalize it first using for example:
String normalizedValue = String.trim(value);
newPrepStatement.setString(1, normalizedValue);
or even direct in SQL like:
SELECT RSCode as id FROM Customer WHERE RSCode=TRIM(?);
In scenario - 1, the query will look like this
"SELECT RSCode as id FROM Customer WHERE RSCode=' 413530'"
In scenario - 2, the query will look like this
"SELECT RSCode as id FROM Customer WHERE RSCode= 413530"