Related
I am trying to multiply a row by a variable (calculated amount):
double servingsMultiplier = 1;
double servingSizeMultiplier = 1;
Calculate the values for "servingsMultiplier" and "servingSizeMultiplier".
String selectQry5 = ("SELECT ci_id, cr_id, ci_ingedient, (ci_amount*servingsMultiplier) AS ci_amount, " +
" (ci_unit*servingSizeMultiplier) AS ci_unit " +
" FROM at_cat_ingredient " +
" WHERE cr_id = ? " +
" ORDER BY ci_ingedient;");
The above works when I use a constant (e.g., 2); however, not when I use a variable. I get the error message:
"SQLException in recipePDF:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
column 'servingsMultiplier' in 'field list'.
An identifier like servingsMultiplier inside the sql statement is not recognized as the value of the variable but as a column name, which of course does not exist.
Use ? placeholders for servingsMultiplier and servingSizeMultiplier in the statement and pass their values just like you pass the parameter in the WHERE clause:
String selectQry5 =
"SELECT ci_id, cr_id, ci_ingedient, " +
"(ci_amount * ?) AS ci_amount, " +
"(ci_unit * ?) AS ci_unit " +
"FROM at_cat_ingredient " +
"WHERE cr_id = ? " +
"ORDER BY ci_ingedient;";
If you want to use mysql variables, then add # before variable name.
SELECT ci_id, cr_id, ci_ingedient, (ci_amount*#servingsMultiplier) AS ci_amount,
(ci_unit*#servingSizeMultiplier) AS ci_unit
FROM at_cat_ingredient
WHERE cr_id = #id
ORDER BY ci_ingedient;
I am trying to use a prepared statement to copy one row to a new row (INSERT)in the same table and include some static values. However, I get the following error:
SQLException in copyProgram: java.sql.SQLException: Operand should contain 1 column(s)
My input is:
prId: 4 accountID: 50 newFromDate: 2020-04-27 newToDate: 2020-04-28
My code is:
String insertQry = ("INSERT INTO at_program "
+ "(acc_id, pr_name, pr_start_date, pr_start_time, pr_end_date, pr_end_time, "
+ "pr_cost_pp, pr_woodbeads, pr_special, pr_joeys, pr_cubs, "
+ "pr_scouts, pr_venturers, pr_rovers, pr_leaders, pr_family, "
+ "pr_swimming, pr_pioneering, pr_archery, pr_canoe, pr_bushwalking, "
+ "pr_4wd, pr_abseiling, pr_snorkelling, pr_boating, "
+ "pr_rock_climbing, pr_caving, pr_branch_instructions, pr_policies_information, "
+ "pr_whs, pr_other, pr_notes) "
+ " (SELECT (?, pr_name, ?, pr_start_time, ?, pr_end_time, "
+ "pr_cost_pp, pr_woodbeads, pr_special, pr_joeys, pr_cubs, "
+ "pr_scouts, pr_venturers, pr_rovers, pr_leaders, pr_family, "
+ "pr_swimming, pr_pioneering, pr_archery, pr_canoe, pr_bushwalking, "
+ "pr_4wd, pr_abseiling, pr_snorkelling, pr_boating, "
+ "pr_rock_climbing, pr_caving, pr_branch_instructions, pr_policies_information, "
+ "pr_whs, pr_other, pr_notes) "
+ " FROM at_program "
+ " WHERE pr_id = ?);");
ps = c.prepareStatement(insertQry, Statement.RETURN_GENERATED_KEYS);
// Create a statement and execute the query on it
ps.setString(1, accountID);
ps.setString(2, fromDate);
ps.setString(3, toDate);
ps.setString(4, prID);
ps.executeUpdate();
You have parens around the field list in your SELECT! Remove them.
The issue is that SELECT expects a list of (individual) columns, but you are passing a multi-column value.
SELECT x, y, z sees x, y and z as three values each consisting of one column, yet you are passing SELECT (x, y, z) which is interpreted as one value with three columns, hence the error.
By the way, the parens around the whole SELECT are superfluous as well, this time because INSERT INTO table (columns) SELECT ... is a recognized syntax construct in itself.
Corrected code:
String insertQry = ("INSERT INTO at_program "
+ "(acc_id, pr_name, pr_start_date, pr_start_time, pr_end_date, pr_end_time, "
+ "pr_cost_pp, pr_woodbeads, pr_special, pr_joeys, pr_cubs, "
+ "pr_scouts, pr_venturers, pr_rovers, pr_leaders, pr_family, "
+ "pr_swimming, pr_pioneering, pr_archery, pr_canoe, pr_bushwalking, "
+ "pr_4wd, pr_abseiling, pr_snorkelling, pr_boating, "
+ "pr_rock_climbing, pr_caving, pr_branch_instructions, pr_policies_information, "
+ "pr_whs, pr_other, pr_notes) "
+ " SELECT ?, pr_name, ?, pr_start_time, ?, pr_end_time, "
+ "pr_cost_pp, pr_woodbeads, pr_special, pr_joeys, pr_cubs, "
+ "pr_scouts, pr_venturers, pr_rovers, pr_leaders, pr_family, "
+ "pr_swimming, pr_pioneering, pr_archery, pr_canoe, pr_bushwalking, "
+ "pr_4wd, pr_abseiling, pr_snorkelling, pr_boating, "
+ "pr_rock_climbing, pr_caving, pr_branch_instructions, pr_policies_information, "
+ "pr_whs, pr_other, pr_notes "
+ " FROM at_program "
+ " WHERE pr_id = ?;");
Get an error when writing to the database
The function for it:
var newMsg = { payload: msg.payload };
newMsg.topic="insert into MyTable (a,b,c,d,e,f,g) values (newMsg.payload)"
The incoming payload debug shows
payload: "B0:AC:A2:AC:07:F4","Ready","893901","860990","online","876","333"
The error I get from the database node (nore-red-node-mysql) is
"Error: ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value
count at row 1"
The strange thing to me is that if I try a
newMsg.topic="insert into MyTable (a,b,c,d,e,f,g) values (\"B0:AC:A2:AC:07:F4\",\"Ready\",\"893901\",\"860990\",\"online\",\"876\",\"333\")"
it works perfectly...
Where is the trick?
There is no trick.
This is because the node-red-node-mysql and node-red-contrib-sqldbs nodes do not do any query substitution.
This means that what gets sent to the database is exactly what is in the msg.topic field. In this case that would have been:
insert into MyTable (a,b,c,d,e,f,g) values (newMsg.payload)
Which mysql will read as trying to pass a single value to a query expecting 7 values.
You will have to build the full query (and do your own variable escaping if needed) in a function node before passing the message to the database node.
at the end I solved it this way:
var data = msg.payload.split(",");
msg.payload = {};
msg.payload.a=data[0];
msg.payload.b=data[1];
msg.payload.c=data[2];
msg.payload.d=data[3];
msg.payload.e=data[4];
msg.payload.f=data[5];
msg.payload.g=data[6];
insert into MyTable (a,b,c,d,e,f,g) values ('" + data[0] + "','" + data[1] + "','" + data[2] + "','" + data[3] + "','" + data[4] + "','" + data[5] + "','" + data[6] + "')";
return msg;
can you check my code?
INSERT INTO tbl_bed
(status,wardID,roomID)
VALUES ('"+ cb_bedStatus.getSelectedItem() +"',
(SELECT wardID FROM tbl_ward
WHERE wardName='"+ cb_wardname.getSelectedItem().toString() +"'
AND category='"+ cb_ward.getSelectedItem().toString() +"'),
(SELECT roomID FROM tbl_room
WHERE roomNo='"+ cb_roomNo.getSelectedItem().toString() +"'))
I got this error when i run the program "Subquery returns more than 1 row".
Im using netbeans & mysql.
You could use
sql = "INSERT INTO tbl_bed (status, wardID, roomID) "
+ "SELECT '"+ cb_bedStatus.getSelectedItem() +"', b.wardID, c.roomID "
+ "FROM tbl_ward b, tbl_room c "
+ "WHERE b.wardName='"+ cb_wardname.getSelectedItem().toString() +"' "
+ "AND b.category='"+ cb_ward.getSelectedItem().toString() +"' "
+ "AND c.roomNo='"+ cb_roomNo.getSelectedItem().toString() +"' "
if there is no risk of SQL injection attacks. Otherwise, put the same SQL into a prepared statement.
I am using Hibernate JPA and Spring with a Mysql database and I want to insert using a SQL statement like this:
Date saveDate = new Date();
java.sql.Timestamp timeStampDate = new Timestamp(saveDate.getTime());
Query persistableQuery = entityManager.createNativeQuery("INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
+ "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES ("
+ true +", " + timeStampDate + ", " + description + ", " + title + ", "
+ needsLevelId + ", " + patientId + ", " + userId + " )");
persistableQuery.executeUpdate();
But after running it I get the following error:
WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: -11, SQLState: 37000
ERROR: org.hibernate.util.JDBCExceptionReporter - Unexpected token: 15 in statement
[INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE,
NEEDS_LEVEL_ID, PATIENT_ID, USER_ID)
VALUES (true, 2011-03-01 15?, any description, , 193, 1, 3 )]
Could someone help me on this please?
PS. I am aware of using hibernate in non-native way, but I need to use native way. I am also of insert ...from... , but I don't think it will help.
Finally I think the problem is mainly with the date. How do you guys pass on MySQL a datetime type using Java?
Update:
The following works fine, I guess it is a java date to mysql datetime conversion problem.
("INSERT INTO TASK_ASSESSMENT "
+ "(ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE, "
+ "NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) "
+ "VALUES (true, 1999-12-22, '" + description + "', '"
+ title + "', " + needsLevelId+", " + patientId
+ ", " + userId + ")");
Could anyone please help me on how to convert java.util.Date to MySQL datetime?
Don't use concatenation to insert data into queries, use parameters instead. It solves problem with wrong representation of values, as well as many other problems:
entityManager.createNativeQuery(
"INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
+ "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES (?, ?, ?, ?, ?, ?, ?)")
.setParameter(1, true)
.setParameter(2, saveDate, TemporalType.TIMESTAMP) // Since you want it to be a TIMESTAMP
.setParameter(3, description)
.setParameter(4, title)
.setParameter(5, needsLevelId)
.setParameter(6, patientId)
.setParameter(7, userId)
.executeUpdate();
Looks like a few issues. Some of your fields should have quotes around them. Also, possibly you need to format the timestamp in a different way, not sure how mysql expects it?
Query persistableQuery = entityManager.createNativeQuery(
"INSERT INTO TASK_ASSESSMENT
(ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
+ "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES ("
+ true +", "
+ "'" + timeStampDate + "'"
+ ", "
+ "'" + description + "'"
+ ", "
+ "'" + title + "'"
+ ", "
+ "'" + needsLevelId + "')");
As far as formatting the date, I suspect you will need to look at the SimpleDateFormat class, which will let you get the date into whatever format mysql expects. See http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
You can send parameter in method save, or what you use and use named SQL queries Query persistableQuery = entityManager.createNativeQuery("INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES (":active_flag",":timeStampDate", ":description", ":title", ":needsLevelId", ":patientId", ":userId" )").setParameter("active_flag", your_object.getactive_flag).setParametr and etc
persistableQuery.executeUpdate();
but somewhere create object with all this fields.
In hibernate 5.3 and above positional parameters are deprecated so we need to use keys for parameter. Hql does not support insert with parameter. We need to follow below approch
import org.hibernate.query.Query;
public void insertData() {
String sql = "insert into employee(id,name,age,salary) values(:0,:1,:2,:3)";
List<Object> paramList = new ArrayList<Object>();
paramList.add(1); // id
paramList.add("sumit"); // name
paramList.add("23"); // age
paramList.add(10000); // salary
Session session = null;
try {
session = getSessionfactory().openSession();
Query query= session.createNativeQuery(sql);
for(int i=0;i<paramList.size();i++) {
query.setParameter(""+i,paramList.get(i)); // remember to add "" before i , we need to maintain key value pair in setParameter()
}
query.executeUpdate();
}
catch(Exception e) {
System.out.println(e);
}
}