Using preparedstatement in Text datatypes

2019-09-16 08:46发布

问题:

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());

回答1:

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.



回答2:

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();}


回答3:

Make it as

ps.setString(1, usermsgmodel.getMessage());