简体   繁体   English

使用java中的Prepared Statement将用户IP地址插入MySql表

[英]Insert user IP Address into MySql table using Prepared Statement in java

I need to insert user IP Address into MySql table using PreparedStatement. 我需要使用PreparedStatement将用户IP地址插入MySql表。 How can I do it? 我该怎么做?

I tried with following code in Servlet. 我尝试使用Servlet中的以下代码。

InetAddress ipaddress;
try {
    ipaddress = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
    e.printStackTrace();
}

I want to know is there any better method than above to get IP Address ?? 我想知道有没有比上面更好的方法来获取IP地址? or I can continue with above code? 或者我可以继续上面的代码?

String insertquery = "insert into tablename (IPAdd) values (?)";

preparedStatement = conn.prepareStatement(insertquery);
preparedStatement.setString(1, ipaddress);// It's not a string so How can I set values here ?// Getting error here

If you want to get the IP then Instead of use : 如果你想获得IP然后而不是使用:

preparedStatement.setString(1, ipaddress);

use : 采用 :

// this will return the IP Host Adresse for example 192.168.1.2
preparedStatement.setString(1, ipaddress.getHostAddress());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM