In PreparedStatement i got an error in this line saying that "the method getMessage return type is Text, So setString property cannot accommodate Text value "
I write a method like
public Text getMessage(){
return message;
}
In my class
PreparedStatement ps;
ps=con.prepareStatement("insert into tblmessage
(message) values(?)");
ps.setString(2, usermsgmodel.getMessage());
ps.executeUpdate();
Text is not type of java.lang.String which causing the compile time error.
PreparedStatement#setString accepts two parameter
parameter index
java.lang.String
I think parameter index should be 1 and you need to set the String which you need to extract from Text value of getMessage method.
Try this
PreparedStatement ps;
ps=con.prepareStatement("insert into tblmessage
(message) values(?)");
ps.setString(2, usermsgmodel.getMessage().getValue());
ps.executeUpdate();
Related
I know that setString permits to insert a value in specified position,
now I want get checkbox values from the jsp page in order to pass it to the database.
I defined the variable of checkbox as a String array since it may handle one or more values.
This is how I defined it the variable in the class:
public String[] rep;
This is how my servlet shall retrieve this parameter in the doPost method:
String[] rep = request.getParameterValues("rep");
and this is a line from my DAO class from the preparedStatement query:
st.setString(3, exam.rep);
but that is shown this error:
The method setString(int, String) in the type PreparedStatement is not applicable for the arguments (int, String[])
the whole query
public static void add(Exam exam) throws ClassNotFoundException, SQLException {
Connection cnx;
cnx = Connect.getConnection();
String req = "insert into examen values (?,?,?)";
PreparedStatement st = cnx.prepareStatement(req);
st.setString(1, exam.titre);
st.setString(2, exam.question);
st.setString(3, exam.rep);
st.executeUpdate();
}
It would help if you can show us your SQL query. Prepared statements take a single value, not an array. As you define the first param as the index of the ? in your query to replace with corresponding second param. Something like this might suit your needs;
String stmt = "INSERT INTO abc (some_field) VALUES (?);";
PreparedStatement ps = conn.prepareStatement(stmt);
String formatted = String.join(",", items);
ps.setString(3, formatted);
If you want to store an array value using your prepared statement then you should format your string in some way that you can convert it back into an array when reading from your DB.
i searched here to find solution for my error but no one match my problem , So is there anyone help me to find the error in my code !?
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
Object selected = list_1.getSelectedValue();
Connection conn = null;
conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
Statement st= conn.createStatement();
String query = "INSERT INTO flyer_item (discount) SELECT price*? FROM `item` where item_name='?' ";
// PreparedStatement ps = null;
int i = Integer.valueOf((textField_1.getText()));
i=i/100;
java.sql.PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1,i);
ps.setString(2, selected.toString());
ps.executeUpdate();
st.executeUpdate(query);
} catch (SQLException se){
System.out.println(se.getMessage());
}
} } );
Note : mysql statement it's running successfully in workbench .
thank you
Remove the single quotes around the question mark placeholder
Change this:
where item_name='?'
To this:
where item_name= ?
That should resolve the problem.
With the single quotes, the prepareStatement is seeing the single quotes as enclosing a string literal. The string literal happens to contain a question mark, but it's not seeing that question mark as a bind placeholder.
So the resulting prepared statement only has a single placeholder. Which is why the setString call is encountering an error: there is no second placeholder to supply a value for.
--
EDIT
Also remove this line from the code:
st.executeUpdate(query);
And also remove this line:
Statement st= conn.createStatement();
(The code is creating and using a prepared statement ps.)
remove the quotes from second parameter. within the quotes ? is treated as literal and not as a parameter.
String query = "INSERT INTO flyer_item (discount) SELECT price*? FROM `item` where item_name=?";
type conversion will autonatically handled..
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=?
In PreparedStatement which method i need to use execute the class
I write a method like
public Text getMessage(){
return message;
}
In my class
PreparedStatement ps;
ps=con.prepareStatement("insert into tblmessage
(message) values(?)");
ps.setString(2, usermsgmodel.getMessage());
ps.executeUpdate();
i got an error in this line saying that "the method getMessage return type is Text, So you setString property cannot accommodate Text value "
ps.setString(1, usermsgmodel.getMessage());
Try following :
public Text getMessage(){
return "Hello"; // or whatever you want to return
}
Class :
PreparedStatement ps;
ps=con.prepareStatement("insert into tblmessage (message) values(?)");
ps.setString(1, usermsgmodel.getMessage());
ps.executeUpdate();
You are only inserting 1 column data in table so you have to use 1 not 2 in ps.setString(1,usermsgmodel.getMessage());
and one question is that where you are setting message ? I don't understand the return message line so I have used Hello.
Use this, it works fine.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hossain?useUnicode=true&characterEncoding=UTF8;","root","root");
PreparedStatement ps=con.prepareStatement("select * from UserTable where name=? and password=?");
ps.setString(1,username);
ps.setString(2,userpass);
ps.executeQuery();
}catch(Exception e){e.printStackTrace();}
Make it as
ps.setString(1, usermsgmodel.getMessage());
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....