gpt4 book ai didi

android - 无法通过servlet向mysql插入数据

转载 作者:行者123 更新时间:2023-11-30 01:29:35 26 4
gpt4 key购买 nike

我正在尝试使用以下方法将数据插入到 mysql 表中,但无法执行此操作。知道我哪里可能出错吗?

方法一:使用HTTPClient直接访问URL。下面是代码:

DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://<lclhst>/GnPServlet/GetNpostServlet/? account=1&password=123");
HttpResponse execute = client.execute(httpPost);

方法二:使用URL连接直接访问URL。下面是代码:

 URL url = new URL("http://<lclhst>/GnPServlet/GetNpostServlet/?    account=1&password=123");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/octet-stream");
conn.connect();

方法三:使用Arraylist传值。

当我从浏览器运行 URL 时,我收到成功消息“已插入”,并且数据已插入到数据库中。但通过应用程序尝试时同样不会插入数据。下面是 servlet 代码:

private String accountLookup(String acct, String pwd)
{
Connection con = null;
Statement st = null;
StringBuffer msgb = new StringBuffer("");

try
{
// These will vary depending on your server/database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbone?user=root&password=root");

Statement stmt = con.createStatement();

stmt.executeUpdate("insert into accttbl(address, description, time) values ('test 07-jul',ok,12:12)");
return "Inserted";
}
catch (Exception e)
{
return e.toString();
}
}

下面的代码插入了数据,但它打开了我不想要的浏览器。此外,数据插入并不总是成功。

 String url = "http://10.0.2.2:8080/GnPServlet/GetNpostServlet";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

最佳答案

conn.setRequestMethod("POST");

看起来您正在发送 POST,而 servlet 需要 GET(如果您将 URL 粘贴到 URL 栏中,浏览器就会发送该消息)

conn.setRequestMethod("GET");

...很可能是您想要的,因为您的参数已编码在 URL 中。

另外,您确定您的网址中帐户前面的空格应该存在吗?

关于android - 无法通过servlet向mysql插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17627729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com