开发者

How to insert variable as a string into MySQL in Java

Suppose I have two variables and I know their values:

v1=11.1f
v2=22.2f

I can insert a string of "11.1,22.2" into a field in this way.

PreparedStatement pstmt = null;
pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1, "11.1开发者_如何转开发,22.2");

but what should I do if I do not know their values. If I do it in the following way,

pstmt.setString(1, "v1,v2");

it is also a string, however, v1 and v2 are just characters but not variables any more.

So how to put variables instead of their values into a String and then I retrieve their values when I need them.

That reason why I asked this question is because I want to put an ArrayList in one row in MySQL. If so I thought I need to put float[] as a string in one field. Please tell me there will be another way to do it.


In general you can create strings with placeholders using:

String result = String.format("%s,%s", v1, v2);

If you are using JDBC, you can use a PreparedStatement, for example:

PreparedStatement statement = connection.prepareStatement("UPDATE table1 SET column1 = ? WHERE column2 = ?");
int i = 1;
statement.setInt(i++, v1);
statement.setInt(i++, v2);
statement.executeUpdate();

For creating JDBC queries the PreparedStatement is preferable because it guards you against typing and character escaping problems.

EDIT: Per request, an alternative way (don't know if it's better though):

MessageFormat form = new MessageFormat("{0},{1}");
Object[] args = new Object[] {v1, v2}; // achtung, auto-boxing
String result = form.format(args)

(this one is on the house, but untested)


Something like this:

// float v1 = 11.1f;
// float v2 = 22.2f;
Hashtable ht = new Hashtable();
ht.put("v1",new Float(11.1));
ht.put("v2",new Float(22.2));
String a = "11.1,22.2";
Enumeration e = hashtable.keys();
while( e. hasMoreElements() ){ 
    String key = e.nextElement();       
    a.replace("/"+e.get(key)+"/",key);
}
System.out.println(a); // prints out "v1,v2"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜