Inserting values in to oracle table using jsp - java

I am using the following code to insert values in to a table.
String sql = "INSERT INTO APPLICATION VALUES (?,?,?,?,?,?,TO_DATE(?,'DD/MMYYYY'),?,TO_DATE(?,'DD/MM/YYYY'),?,?,?,?,?,SYSDATE,'X',?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,Integer.parseInt(sr));
pstmt.setString(2,nm);
pstmt.setString(3,(String)session.getValue("ITSGTYP"));
pstmt.setString(4,pst);
pstmt.setString(5,dox);
pstmt.setString(6,zo);
pstmt.setString(7,dob);
pstmt.setString(8,cdr);
pstmt.setString(9,cdrdt);
pstmt.setString(10,qual);
pstmt.setString(11,mail);
pstmt.setString(12,bond);
pstmt.setInt(13,Integer.parseInt((String)session.getValue("USER")));
pstmt.setString(14,request.getRemoteAddr());
pstmt.setString(17,place);
The description of the table into which the values are inserted is as follows
EMP_ID NOT NULL NUMBER(6)
NAME VARCHAR2(25)
APPLN_TYP VARCHAR2(10)
POST VARCHAR2(100)
DIV VARCHAR2(25)
ZONE VARCHAR2(5)
DOB DATE
CADRE VARCHAR2(5)
CADRE_DATE DATE
QUALIFICATION VARCHAR2(100)
EMAIL_ID VARCHAR2(70)
BOND VARCHAR2(3)
SUBMITTED_BY NUMBER(6)
SUBMIT_IP VARCHAR2(30)
SUBMIT_DATE DATE
FLAG VARCHAR2(1)
PLACE VARCHAR2(20)
While executing the above code I am getting the following error
Error: java.sql.SQLException: Invalid column index
This query was working fine before.
My previous table didn't have the PLACE column. I had to insert it at a later point.

It's safer to include the columns names you want to insert into the SQL statement like:
String sql = "INSERT INTO APPLICATION VALUES (EMP_ID,NAME, ....) // etc
(?,?,?,?,?,?,TO_DATE(?,'DD/MMYYYY'),?,TO_DATE(?,'DD/MM/YYYY'),?,?,?,?,?,SYSDATE,'X',?)";
In this way, you have more control of the indexes and the columns you are using in your statement.

Replace pstmt.setString(17,place);
with
pstmt.setString(15,place);
The reason for error you get is :
You don't have 17 ? symbols in your query for prepared statement, you only have 15 ? symbols that means you can only set 15 values (for 15 columns) for that prepared statement.
Now what you were doing is you were setting a parameter at 17 th index and you don't have any column specified at index 17 in your query, you only have 15 columns and 15 ? symbols for the values to be inserted at respective 15 columns.
So replace it with what I mentioned above and it will work.

In your query u have 15 parameters to set. And you are trying to give value of 17th index. You should change it to 15 instead of 17.
i.e
pstmt.setString(15,place);

Related

The column name is not valid - error

I am getting this error while I am fetching value from resultset.
Error : com.microsoft.sqlserver.jdbc.SQLServerException: The column name company.short_name is not valid
CASE 1 :
select company.short_Name,location_name from company,location;
this query is executing fine on SQL Server but in my java code when I trying to retrieve value like resultset.getString("company.short_name"); that time this give the above error.
CASE 2 :
select company.short_Name short_name,location_name from company,location;
and retrieve value like resultset.getString("short_name"); than it work fine with both database MySQL and MSSQL.
I am migrating my database from MySQL to MSSQL.above case 1 is work fine in MySQL, but why it is not work in MSSQL?
resultset.getString("company.short_name"); is wrong here. No need to specifying fully qualified name while trying to fetch the data in your application. Just specify the column name like resultset.getString("short_name");.
Cause even though you say select company.short_Name ... query out the column name as short_Name since that's what defined in table schema.
In case both tables has same column which may result in ambiguity, give a alias name to the columns like
select company.short_Name as company_shortname,
location.short_Name as location_shortname,
location.location_name from company,location;
add the following to your application.properties file
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
When you do
select company.short_Name,location_name from company,location;
This query outs the column name short_Name and resultSet would also have short_Name
since the company.short_name doesnt exist you get an error.
the function resultset.getString(String columnLabel)
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
Parameters:
columnLabel the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is null
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set
in the function resultset.getString(String columnLabel), the arg is a column name for executing sql, the statement select company.short_Name,location_name from company,location; will get a result set, which has table headers short_Name,location_name

MySQL Simple Query Error

I am new to MySQL and I wrote a simple query bellow:
CREATE Table tblFeedBack
(
`FeedBackID` INT AUTO_IncremeNT,
`UserID` INT,
`Inserted_TS` TIMESTAMP ,
`FeedBackValue` VARCHAR(100),
PRIMARY KEY (FeedBackID)
);
CREATE PROCEDURE tblFeedBack_InsertUpdate
(
IN U_ID INT,
IN FB_Value VARCHAR(50)
)
BEGIN
IF ((Select COUNT(*) From 'tblFeedback') < 3)
BEGIN
INSERT INTO 'tblFeedBack' (`UserID`,`FeedBackValue`)
VALUES (U_ID,FB_Value);
END
ELSE
BEGIN
DECLARE #MostRecentFID INT;
SELECT TOP 1 `FeedBackID` FROM tblFeedback
WHERE UID = U_ID
ORDER BY `Inserted_TS` DESC
INTO #MostRecentFID;
UPDATE tblfeedback
SET `FeedBackValue` = #FeedBackValue
WHERE `FeedBackID` = #MostRecentFID
END
END
I am getting this error:
Schema Creation Failed: 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 ''tblFeedBack' (`UserID`,`FeedBackValue`) VALUES (1,'12')' at line 9
Can anyone please help me solve this one?
Thanks in advance.
MySQL does not supportĀ TOP you want to use LIMIT 1 instead as they are ordered.
Select `FeedBackID` FROM tblFeedback
WHERE UID = U_ID
ORDER BY `Inserted_TS` DESC
LIMIT 1
INTO #MostRecentFID;
Also, when you query a table using quotes it becomes case sensitive.
IF ((Select COUNT(*) From 'tblFeedback') < 3)
Should be
IF ((Select COUNT(*) From 'tblFeedBack') < 3)
Fix these 2 errors and it should work.
The table names are different in the insert query. One contains 'tblFeedback' and other contains 'tblFeedBack'
Also, please try to remove single quotes near table names in the query.

Using DB2 Sequence in Java Prepared Statement

I want to get the next value of a db2 sequence if the placeholder in the preparedstatement is 0 . How can i do that .
PreparedStmt.setLong(1, attributeID);
So here if attributeID is 0, i want to get the next value from the sequence, other wise i use the attribute ID .
I tried using
PreparedStmt.setObject(1, attributeID > 0 ? attributeID : next val for my seq);
but this does not work !
It's to easy, just get the sequence like you get a result set with executeQuery() method. Then the select statement is:
SELECT SEQ_NAME.NEXTVAL FROM SYSIBM.SYSDUMMY1
The other part is an if sentence. That's all you need to do.
You can declare the primary key column as
ATTRIBUTEID BIGINT GENERATED BY DEFAULT AS IDENTITY
To insert a row with a specific value, include the primary key column in the sql and set its value with:
PreparedStmt.setLong(1, attributeID);
To insert a row where database generates a value for key, omit the primary key column in the sql and do not set its value in the prepared statement.

How to get the serial id just after inserting a row? [duplicate]

This question already has answers here:
How to get a value from the last inserted row? [duplicate]
(14 answers)
Closed 9 years ago.
I have a table with row 'id' (a primary key) default set to serial in PostgreSQL. I insert into this row by calling
session.getCurrentSession().createSQLQuery("some insert query")
without adding any value into id as it is default set to serial.
How can I retrieve the `id' of just inserted row?
JDBC statements can return the generated keys. For instance, if the table has a single column id of type serial (probably PK) that is not mentioned in the insert SQL below, the generated value for this column can be obtained as:
PreparedStatement s = connection.createStatement
("INSERT INTO my_table (c,d) VALUES (1,2)",
Statement.RETURN_GENERATED_KEYS);
s.executeUpdate();
ResultSet keys = s.getGeneratedKeys();
int id = keys.getInt(1);
This is faster than sending the second query to obtain the sequence value or max column value later. Also depending on circumstances these two other solutions may not be not be thread safe.
Since it is serial you can use select max(id) from tableName
Using max(id) is a very bad idea. It will not give you the correct result
in case of multiple concurrent transactions. The only correct way is to use
curval() or the returning clause.
In posgresql: There is already a stackoverflow-question exists BTW.
`INSERT INTO tableName(id, name) VALUES(DEFAULT, 'bob') RETURNING id;`
(also)
Get a specific sequence:
SELECT currval('name_of_your_sequence');
Get the last value from the last sequence used:
SELECT lastval();
Manual: http://www.postgresql.org/docs/current/static/functions-sequence.html
For PHP-mysql users:
From php.net clickhere
<?php
$link = mysqli_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysqli::$connect_error() );
}
mysqli::select_db('mydb');
mysqli::query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysqli::$insert_id());
?>
But you need to connect for every query.
use SELECT CURRVAL(); . Typically used in conjunction with pg_get_serial_sequence
postgreSQL function for last inserted ID

Mysql&MSAccess: insert into table which have an incremented field

I am sorry if there is a duplicate but I tried all ways still I can't do the insertion.
I have a table with only two fields ( ID , Name )
When I run this SQL code it must be insert a new record and increment the ID field automatically
because it's auto increment but unfortunately don't work .
See the trail and errors :
MYSQL :
PreparedStatement pr = con.prepareStatement("insert into names(name) values(?)");
pr.setString(2,"Azad");
java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
insert into names(id,name) values(?,?)
java.sql.SQLException: No value specified for parameter 1
MS Access :
insert into names(name) values(?)
java.lang.ArrayIndexOutOfBoundsException: 1
insert into names(id,name) values (?,?)
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect
What's the reason of those errors ? and how to solve it ?
Thanks for suggestions and answers.
change pr.setString(2,"Azad"); to pr.setString(1,"Azad");
The first parameter is related to the position of the ? in the prepared statement, not the column index in the table.
java.sql.SQLException: No value specified for parameter 1. This is down to the fact that you have specified two parameters for the query. But have only specified one value, for the second parameter. If "ID" is an auto incremented column then you don't need to pass in a value. If its not then
pr.setString(1,IDVALUE);
pr.setString(2,"Azad");

Categories