Invalid column index , update using PreparedStatement - java

I am updating table using PreparedStatement
the following code works perfectly
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname = 'java10'");
int i = pst.executeUpdate();
but when i tried like this it throwing exception
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname =?");
pst.setString(2, "java10"); // yeah second column is jfname
int i = pst.executeUpdate();
stacktrace :
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.java:5330)
at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5318)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setString(OraclePreparedStatementWrapper.java:282)
at com.indus.database.EmployeeDTO.updateData(EmployeeDTO.java:114)

2 in following refers to the position of the question mark in query string, not to the position of column in database table and not to the order of column names used in query:
pst.setString(2, "java10"); // yeah second column is jfname
Use 1 instead.
pst.setString(1, "java10"); // first question mark is jfname

Please go through the setString() method specs:
http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html#setString%28int,%20java.lang.String%29
The correct approach is :
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname =?");
pst.setString(1, "java10");
int i = pst.executeUpdate();

Related

Populate JCombobox values depending on another JCombobox

I have two JComboboxes A and B, so if I select any item form A then values related to the item selected in A should fill in JCombobox B. I tried this but get an error:
java.lang.ArrayIndexOutOfBoundsException: 0
at pst.setString(1, client.getSelectedItem().toString());
try
{
String query="select `User_Name` from Client where `Client_Name`='?' ";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, client.getSelectedItem().toString());
ResultSet rs=pst.executeQuery();
user.addItem("--Select--");
while(rs.next())
{
user.addItem(rs.getString("User_Name"));
}
// return;
System.out.println(query);
}
catch(Exception g)
{
g.printStackTrace();
}
The PresparedStatement takes care of quoting the parameter, when you use setString()
Try
String query="select User_Name from Client where Client_Name = ?";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, String.valueOf(client.getSelectedItem()));
I guess that when you use '?' the prepared statement does not count this as parameter and this is why you get the IndexOutOfBounce
you have done a mistake ,
no need to use '?' , it should be just Client_Name=?

what does parameterIndex mean in this syntax pst.setString(parameterIndex, x);?

I have a code as follow:
String query = "select * from EmployerData where userName = ? and password = ?";
PreparedStatement pst = connect.prepareStatement(query);
pst.setString(1, textField.getText()); // what 1 refers to
pst.setString(2, passwordField.getText()); // 2
which is working perfectly as I want but I get confused about the meaning of parameterIndex. What does parameterIndex mean???
It tells the query which question mark to replace. The first question mark - index 1. The second question mark - index 2.

Getting null value in the foreign key field of my table in Mysql

I have 2 tables in my application:
1.newuser
2.introducer_table
Newuser1 table contains *sid**(primary key,auto-generated field)****, fathername,gender,datebirth,occupation,addharnumber as columns
1.I’m inserting values into the newuser table using java prepared statement like below:
PreparedStatement pst = con.prepareStatement("insert into newuser1 (name,fathername,gender,datebirth,occupation,aadharNumber) values(?,?,?,?,?,?)");
//pst.setString(1,NULL);
pst.setString(1,”xyz”);
pst.setString(2,"ram");
pst.setString(3,"male");
pst.setString(4,"oct25");
pst.setString(5,"emps");
pst.setString(6,"4564");
data is inserted successfully,but I want the sid value of newuser1 in my introducer_table so I write the query like this in prepared statement to select the last insert id.
My introducer_table contains the columns:
**sid(foreign key),name,accountno,sign**
PreparedStatement pst = con.prepareStatement("insert into introducer_table(sid,name,accountno,sign) values((SELECT LAST_INSERT_ID() from dual),?,?,?)");
//nomine details into data base
//pst.setString(1,NULL);
pst.setString(1,"ram");
pst.setString(2,"8945");
pst.setString(3,"ssss");
When I execute this,Im getting ‘0’ value in the sid column of introducer_table.I make sid column as not null while creating intoducer_table,even im getting the ‘zero’ value like this:
Introducer_table:
**Sid** name accountno sign
**0** ram 8945 ssss
Please help me I was stucked by this problem from so many days.
Rather than doing it your way think about using
con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
and then after your insert
pst.executeUpdate();
ResultSet rs = prest.getGeneratedKeys();
  
int last_inserted_id = -1;
if(rs.next())
{
last_inserted_id = rs.getInt(1);
}

How do I insert last_insert_id using preparedStatement?

I am facing difficulty in inserting " last_insert_id" in my prepared statement.I got how to select the last_insert_id in prepared statement like below:
PreparedStatement getLastInsertId = con.prepareStatement("SELECT LAST_INSERT_ID()");
When I use the same procedure for inserting last_insert_id in my preparedstatement like this:
1. PreparedStatement pst = con.prepareStatement("insert into introducer_table values(?,?,?,?)");
2.
3. //introducer details into database
4. pst.setString(1,LAST_INSERT_ID());
5. pst.setString(2, nameofintroducer);
6. pst.setString(3, accountno);
7. pst.setString(4, signofintroducer);
Im getting 'null' value in the first column.can any one help me to come out from this problem
If your doing both the save actions at a time use getGeneratedKeys(), It's pretty much java.
I'm not a SQL guru, but here I found a way to get the generated id using getGeneratedKeys()
long generatedId= 0L;
statement = con
.getConnection()
.prepareStatement(
"insert into new_user set name= ? , contact= ? , ....",
statement.RETURN_GENERATED_KEYS);
statement.setString(1, "examplename");
statement.setString(2, "examplecontact");
------
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
generatedId = generatedKeys.getLong(1);// here is your generated Id , use it to insert in your introducer_table
}
PreparedStatement pst = con.prepareStatement("insert into introducer_table values(?,?,?,?)");
//introducer details into database
pst.setString(1, generatedId);
pst.setString(2, nameofintroducer);
pst.setString(3, accountno);
pst.setString(4, signofintroducer);

Help needed for inserting values to a mysql table

I have created a table using mysql:
CREATE TABLE JobCard (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
JobNo Long,
RegNo VARCHAR(20),
Service_Type VARCHAR(20),
Customer_Complaints VARCHAR(100)
);
in cmd.
From Eclipse, i coded for inserting the values using prepared Statement for the table. Since ID is a auto_increment, i didn't include it in the insert statement.
String Query =
"INSERT INTO JobCard (JobNo, RegNo, Service_Type, Customer_Complaints)
VALUES (?,?,?,?)";
But the output shows me :
java.sql.SQLException: Parameter index out of range
(5 > number of parameters, which is 4).
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at
com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3717)
at
com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3701)
at
com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4552)
at
example.Connect.DoInsertIntoDB(Connect.java:40)
Can anyone please tell me how to pass the parameter list? Please help me resolve this error!!
Update:
Here is my code:
The method call is:
System.out.println(strLine);
String[] dbColumnValues = strLine.split("%");
Connect.DoInsertIntoDB(Long.parseLong(dbColumnValues[0]),dbColumnValues[1],dbColumnValues[2], dbColumnValues[3]);
The method definition:
public static void DoInsertIntoDB(Long JobNo, String RegNo, String Service_Type, String Customer_Complaints){
String Query = "INSERT INTO JobCard (JobNo, RegNo, Service_Type, Customer_Complaints) VALUES (?,?,?,?)";
try {
Connection conn = toConnect();
PreparedStatement pstmt = conn.prepareStatement(Query);
pstmt.setLong(2, JobNo);
pstmt.setString(3, RegNo);
pstmt.setString(4, Service_Type);
pstmt.setString(5, Customer_Complaints);
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Need to read your stack trace. In your code (on line 40 of Connect.java) you're attempting to set a value into the 5th ? but there are only 4 ?s in your prepared statement.
When you set the parameters, you are starting with 2, and it must be 1.
If you see, the last parameter is the index 5, and you don't have a 5° parameter,
Because of this java say the exception "Parameter index out of range".
You must start in 1.
PS: Sorry for my english.
Prepare statement parameter begin from 1 number, based on your code the parameter should be 1 to 4
but you ended with 5.
it cause parameter index out of range
Your try should look like this,
try {
Connection conn = toConnect();
PreparedStatement pstmt = conn.prepareStatement(Query);
pstmt.setLong(1, JobNo);
pstmt.setString(2, RegNo);
pstmt.setString(3, Service_Type);
pstmt.setString(3, Customer_Complaints);
pstmt.executeUpdate();
pstmt.close();
conn.close();
}
and that should solve the problem....

Categories