无法通过servlet将数据插入mysql

时间:2013-07-13 06:42:08

标签: android mysql insert

我正在尝试使用以下方法将数据插入到mysql表中,但我无法这样做。我知道我可能会出错的地方吗?

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

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

方法2:使用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();

方法3:使用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);

1 个答案:

答案 0 :(得分:0)

conn.setRequestMethod("POST");

当servlet期望POST时(如果您只是将URL粘贴到URL栏中,浏览器将发送的内容),您似乎正在发送GET

conn.setRequestMethod("GET");

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

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