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());
Related
Can anyone Tell how can I modify my code so I can save data in my Database.
My code is:
private Class nextPage;
#OnEvent(component="submitButton")
Object onSubmitFromSubmitButton()
{
String flag="";
String jndiname="jdbc/TestDB";
DataSource dataSource=null;
try{
dataSource=(DataSource) new InitialContext().lookup("java:comp/env/" + jndiname);
Connection con=dataSource.getConnection();
Statement stm=con.createStatement();
ResultSet rs=stm.executeQuery("insert into recenzii (numeRecenzor,nivelIncredere,idHotel,recenzie) values (?,?,?,?)");
ResultSetMetaData rsmd=rs.getMetaData();
while(rs.next())
{
rs.getString("numeRecenzor");
rs.getString("recenzie");
rs.getInt("nivelIncredere");
rs.getInt("idHotel");
}
}catch (Exception e){flag+=e.toString();}
if (dataSource!=null)
flag+=" succes";
System.out.println("Datele au fost trimise cu succes! "+flag);
return nextPage;
}
}
I tried to put ExecuteUpdate or Execute instead of ExecuteQuery but I got some errors on the code that says it can't convert type int to ResultSet. I am new to this so I would appreciate if anyone could tell me what to modify.
Thank you!
ResultSet object is used to retrieve data from database.
If you want to insert data, you can either supply the data to insert within the query and call stm.executeUpdate("insert ...")
or you can use PreparedStatement (there are more options, but these are easiest).
You may want to try something similar to this:
PreparedStatement preparedStatement = con.prepareStatement("insert into recenzii (numeRecenzor,nivelIncredere,idHotel,recenzie) values (?,?,?,?)");
preparedStatement.setString(1, "val1");
preparedStatement.setString(2, "val2");
preparedStatement.setInt(3, 3);
preparedStatement.setInt(4, 4);
preparedStatement.executeUpdate();
I converted date datatype to string and stored in table as a string.I want to write a query to show results between certain date.I wrote like this
public Statement getstatement(Statement s) throws SQLException {
long accid=0;
Statement s1=null;
Connection conn=DatabaseUtil.getConnection();
PreparedStatement psmt=conn.prepareStatement("select * from Account_groupc_tja05 where Account_id =?");
psmt.setLong(1,s.getAccid());
System.out.println("inside dao");
ResultSet rs=psmt.executeQuery();
while(rs.next()){
accid=rs.getLong(1);
System.out.println("inside while");
}
if(s.getAccid()==accid){
System.out.println("inside if");
PreparedStatement psmt1=conn.prepareStatement("select * from deposit1_groupc_tja05 where Account_id =? and Transaction_Date between ? and ?");
psmt1.setLong(1, accid);
psmt1.setString(2, s.getDatefrom());
psmt1.setString(3, s.getDateto());
System.out.println(s.getDateto());
ResultSet rs1=psmt1.executeQuery();
while(rs1.next()){
System.out.println("inside inner while");
s1=new Statement(rs.getString(6),rs.getLong(7),rs.getLong(4),rs.getLong(3),rs.getString(5));
System.out.println(s1);
}
}
return s1;
}
But this query is not executing. Why?
Your syntax is wrong, there is nothing like Prepared statement and you'd want to execute the ps to "execute the query". e.g.
PreparedStatement ps=con.prepareStatement("Select * from deposit where transaction_date between ? And ?");
ps.setString(1,fromdate);
ps.setString(2,todate);
ps.execute();
ps.close();
Also you need to enter your database credentials in your connection statement
Connection conn=DatabaseUtil.getConnection();
to
Connection conn=DatabaseUtil.getConnection(<databaseurl>, <username>, <password>);
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=?
When I debug, I get this error :
Column 'place1' not found.
I was able to verify that it has column place1 in sql.
Is it because I can not have two database connection in one function? I am unsure on how to further debug the problem.
Case.java
System.out.println("The highest value is "+highest+"");
System.out.println("It is found at index "+highestIndex+""); // until now it works fine
String sql ="Select Day from menu where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
int kb=rs.getInt("Day");
System.out.println(kb);
if(kb==k) // k is a value getting from comboBox
{
String sql1 ="Select * from placeseen where ID =?";
DatabaseConnection db1 = new DatabaseConnection();
Connection conn1 =db1.getConnection();
PreparedStatement ps1 = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs1 = ps.executeQuery();
if (rs1.next())
{
String aaa=rs1.getString("place1");
String bbb=rs1.getString("place2");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
DispDay dc=new DispDay();
}
ps1.close();
rs1.close();
conn1.close();
}
else
{
System.out.print("N");
System.out.println("Sorry!!!");
}
}
ps.close();
rs.close();
conn.close();
Trace your code to see where you're getting the data. The error is on this line:
String aaa=rs1.getString("place1");
Where does rs1 come from?:
ResultSet rs1 = ps.executeQuery();
Where does ps come from?:
PreparedStatement ps = conn.prepareStatement(sql);
Where does sql come from?:
String sql ="Select Day from menu where ID =?";
There's no column being selected called place1. This query is only selecting a single column called Day.
Maybe you meant to get the result from the second prepared statement?:
ResultSet rs1 = ps1.executeQuery();
There are probably more such errors. Perhaps several (or many) more. Because...
Hint: Using meaningful variable names will make your code a lot easier to follow. ps, ps1, rs1, etc. are very easy to confuse. Name variables by the things they conceptually represent and your code starts to read like a story which can be followed. Variable names like daysQuery and daysResults and placesResults make it more obvious that something is wrong when you try to find a "place" in a variable which represents "days".
In your second query:
PreparedStatement ps1 = conn.prepareStatement(sql);
you are accidentally using the variable sql instead of your previously defined sql1. Replace it and it will be ok.
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();