I have an insert query for Sybase Db which inserts one varchar value and 2 integer values into a table which is returning a error.
The table column datatypes are Varchar,Int,Int
The query is as shown below
sql_str = "INSERT INTO TempTable VALUES(" +
"'"+ 'Y' +"',"+ "DateDiff(ss,'12/31/1969 19:00:00','"+ secBegin +"')" +","+ "DateDiff(ss,'12/31/1969 19:00:00','"+ secEnd +"')" +")";
and its uses 2 String values i.e. secBegin and secEnd
String secBegin = "04/03/2012 10:08:24";
String secEnd = "04/03/2012 10:09:07";
And I'm getting the following error:
com.sybase.jdbc3.jdbc.SybSQLException: Insert error: column name or number of supplied values does not match table definition.
and its pointing to the insert query shown above as the erreneous line.
Is there any error in the jdbc query shown above.
Hi you can try this should it work :
sql_str = "INSERT INTO TempTable VALUES("Y",DateDiff(ss,'12/31/1969 19:00:00','"+ secBegin +"'),DateDiff(ss,'12/31/1969 19:00:00','"+ secEnd +"'))";
Related
I'm trying to use query to insert the entirety of one table into another (so no where clause). I am using java (exlipse). I want to insert data into JJ from ENTER
My code:
Edit: the ur variable is set at an earlier point so I don't have to type it a million times.
Connection con = DriverManager.getConnection(ur);
String sql = "INSERT INTO JJ ( Date, Account, Amount, DrCr )"
+ "SELECT ENTER.Date, ENTER.Account, ENTER.Amount, ENTER.DrCr"
+ "FROM ENTER;";
I'm getting the error:
CAExc:::5.0.0-SNAPSHOT unexpected token: ; in statement [INSERT INTO JJ ( Date, Account, Amount, DrCr )SELECT ENTER.Date, ENTER.Account, ENTER.Amount, ENTER.DrCrFROM ENTER;]
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatemen
I try to insert a String into a hsqldb an it gives me this error:
> java.sql.SQLSyntaxErrorException: user lacks privilege or object not
found: S
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(Unknown Source)
the column is set to VARCHAR(50) and the sqlstring is build like this:
String sql = "INSERT INTO Emergency Values(" + Counter.emergencyID + ","+
emergency.status +"," + "\""+ emergency.typeD +"\"" + "," + "\""+
emergency.typeB +"\"" + ","+ emergency.floorID + ")";
this ist how i execute the query:
Statement st = null;
st = con.createStatement(); // statements
int i = st.executeUpdate(sql); // run the query
PS: I know i am open to a sqlInjection like this.
EDIT: values are
sql = "INSERT INTO Emergency Values(0,1,"S","IB",1)"
If i change the string to ;
String sql = "INSERT INTO Emergency Values(" + Counter.emergencyID + ","+
emergency.status +","+ emergency.typeD +","+ emergency.typeB +","+
emergency.floorID +")";
the same error occures
Use a PreparedStatement and you won't have problems:
String sql =
"INSERT INTO Emergency (emergency_id, status, type_d, type_b, floor_id) " +
" Values (?, ?, ?, ?, ?)";
Note that I explicitly listed the column names in the insert statement. Not doing that is considered bad coding style.
I had to guess those names as you didn't show us the definition of your table. You have to replace with the correct column names of your table.
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, Counter.emergencyID);
pstmt.setInt(2, emergency.status);
pstmt.setString(3, emergency.typeD);
pstmt.setInt(4, emergency.typeB);
pstmt.setInt(5, emergency.floorID);
int i = pstmt.executeUpdate(sql); // run the query
The root cause of your problem was the incorrect usage of double quotes: ". String constants have to be put in single quotes in SQL. 'foobar' is a string value. Double quotes are used for identifiers "foobar" is e.g. a column name.
Unrelated, but: the use of Counter.emergencyID lets me think that your are generating (or trying to) unique IDs in your application. Don't do that. Use a sequence or identity column in the database. Do it correctly from the beginning. For a single user application this might not make a difference, but there is no way you can implement that correctly and scalable in an application that is used by multiple users at the same time, with concurrent transactions inserting into the same table.
i found the error in #a_horse_with_no_name 's code
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, Counter.emergencyID);
pstmt.setInt(2, emergency.status);
pstmt.setString(3, emergency.typeD);
pstmt.setInt(4, emergency.typeB);
pstmt.setInt(5, emergency.floorID);
int i = pstmt.executeUpdate(sql); // run the query
note the last line, it should be
int i = pstmt.executeUpdate(); // run the query
please refer to HSQLDB cryptic exception message: "feature not supported"
I know the question is old, but I ran into the same problem and found my a solution without using PreparedStatements.
INSERT INTO TypeA (id) VALUES ("Hello");
failed (user lacks privilege or object not found: Hello ), but
INSERT INTO TYPEA (id) VALUES ('Hello');
worked. So it seems like double quotes are not accepted (see also http://www.hsqldb.org/doc/1.8/guide/ch09.html#expression-section )
I am developing a java web service that is deployed in wildly. It is connected to a postgresql database.
In this database, I have a table called xx_activity. In it there is a column called "id", which is also the primary key.
Here is the query used to create the table:
CREATE TABLE xx_activity
(
id serial NOT NULL,
baseitemid integer
);
to connect to this table, I use the following java code:
conn = postgresVoyateDBConnection();
query = conn.prepareStatement("select id, baseitemid" +
"from xx_activity " +
"where \"id\" = ? ");
query.setInt(1, id);
ResultSet rs = query.executeQuery();
However, when I call the method that includes this code, I get an error:
org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
This is confusing because I certainly have this column. i added escape characters as per this answer, but it did not solve the issue.
Also note that queries without the where clause, like:
conn = postgresVoyateDBConnection();
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity");
ResultSet rs = query.executeQuery();
work perfectly.
I have also tried without using escape characters but it gives the same error. I also checked in pgadmin and there is no trailing space in the column name, neither are there any upper case letters involved (in which case, the other select query shouldn't have worked?).
How can this be fixed?
Fixed this, the issue was a missing space. After the first line of the query, there needs to be a space as belows:
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity " +
"where \"id\" = ? ");
EDIT: escape charactors not needed for id; so final answer should be:
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity " +
"where id = ? ");
I am trying to insert values into a table using jdbc driver. In my table, one column is defined as array datatype.
Table as follows
CREATE TABLE userType
(
id bigserial NOT NULL, // auto Inc
type character varying,
userRole bigint[] // array
)
I am having an array in my code, which is converted from arraylist.
List<Long> ids = new ArrayList<Long>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
Long[] idArr = new Long[ids.size()];
idArr = ids.toArray(idArr);
I am using the following code to insert the data in table.
String querys = "insert into userType(type,fk_last_modified_by,userRole)"
+ " values ('Auto',1,"+ idArr+")";
Connection connections = sessionFactory.getCurrentSession().connection();
Statement stmts = connections.createStatement();
int count =stmts.executeUpdate(querys);
System.out.println("count---"+count);
connections.close();
I am getting the following error while executing the above.
org.postgresql.util.PSQLException: ERROR: syntax error at or near "["
Position: 99
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302)
at org.apache.commons.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:196)
at com.mmf.controllers.UpdateReconcileController.save(com.mmf.controllers.UpdateReconcileController:123)
Then I just followed the solution provided by Jagdesh,
String querys = "insert into userType(type,fk_last_modified_by,userRole)"
+ " values (?,?,?)";
System.out.println(querys);
Connection connections = sessionFactory.getCurrentSession().connection();
CallableStatement stmts = connections.prepareCall(query);
stmts.setString(1, "Auto");
stmts.setInt(2, 1);
stmts.setArray(3, connections.createArrayOf("integer", idArr));
stmts.executeUpdate(querys);;
connections.close();
Now I am getting the following error,
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:53)
at org.postgresql.core.v3.SimpleParameterList.setLiteralParameter(SimpleParameterList.java:114)
at org.postgresql.jdbc2.AbstractJdbc2Statement.bindLiteral(AbstractJdbc2Statement.java:2172)
at org.postgresql.jdbc2.AbstractJdbc2Statement.setLong(AbstractJdbc2Statement.java:1227)
at org.apache.commons.dbcp.DelegatingCallableStatement.setLong(DelegatingCallableStatement.java:252)
Can anyone point me where I am doing mistake?
Instead of above use PreparedStatement
String querys = "insert into reconcile_process (process_type,fk_last_modified_by,fk_bank_stmt_id)"
+ " values (?,?,?)";
Connection connections = sessionFactory.getCurrentSession().connection();
PreparedStatement pstmts = connections.createStatement();
pstmts.SetString("Auto");
pstmts.SetInt(1);
pstmts.setArray(3, conn.createArrayOf("integer", idArr));
pstmts.executeUpdate(querys);
insert into reconcile_process (process_type,fk_last_modified_by,fk_bank_stmt_id) values ('Auto',1,'[Ljava.lang.Long;#b318fc5')
So you cannot just + a long type to a string.
I think you want to use a PreparedStatement, not CallableStatement.
CallableStatements are used for calling a SQL function, and it has kinda weird syntax.
I have a table TotalSales on my database with columns Date(Primary) and Sales. I send query thru my Java Program.
I want to add a row if Date row not exists, and if Date row exists, the value on Sales will be updated. On update, the new value on Sales will be 'current value on Sales' + 'the value of variable totalBill'.
Lets say before execution: row under Sales = 0,
after execution: row under Sales = Sales + totalBill;
I tried this code:
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(date, totalBill)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
st = con.prepareStatement(query);
st.execute();
But doesn't work:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'totalBill' in 'field list'
Can anyone help?
You need to take advantage of the parameterised nature of PreparedStatements and bind the values you want to apply before you execute the statement, something like...
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(?, ?)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+?";
st = con.prepareStatement(query);
st.setDate(1, date);
st.setLong(2, totalBill);
st.setLong(3, totalBill);
for example
Take a look at Using Prepared Statements for more details
You are not appending the variable to your insert query, rather simply using a string. So change this:
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(date, totalBill)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
to
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(" + date + "," + totalBill + ")
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
ADVICE: But for this case, you should learn to use PreparedStatement