1

我正在开发一个 android 项目,我正在尝试获取用户在 EditText 框中输入的文本并将其添加到我服务器上的 SQL 表中。我认为问题出在没有正确的 SQL 查询,但我不确定我必须添加什么(当涉及到 SQL 时我一无所知):S

当我在手机上运行这个应用程序时,它似乎承认我输入了一些内容并将其传递给数据库(没有出现错误或异常),但实际上没有任何内容添加到数据库表中。

任何关于我哪里出错的想法将不胜感激!

JDBC 服务器代码:

public class DBServlet4 extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws IOException, ServletException {

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            Connection con = null;
            Statement stmt = null;
            ResultSet rs = null;

            try {
                    Class.forName("com.mysql.jdbc.Driver");
                                    con = DriverManager.getConnection(
                                    "jdbc:mysql://localhost:3306/cs2001", "l2g0",
                                    "l2g0");

                    stmt = con.createStatement();

                    stmt.executeUpdate("CREATE TABLE IF NOT EXISTS Students (id int, name varchar(45))");
                    stmt.executeUpdate("INSERT INTO Students (id, name) SELECT * FROM (SELECT '0', 'Michael') AS Temp WHERE NOT EXISTS (SELECT name FROM Students WHERE name = 'Michael') LIMIT 1");

                    //con.commit();

            } catch (SQLException e) {
                    throw new ServletException(e.getMessage());
            } catch (ClassNotFoundException e) {
                    throw new ServletException("JDBC Driver not found.", e);
            } finally {
                    try {
                            if (rs != null) {
                                    rs.close();
                                    rs = null;
                            }
                            if (stmt != null) {
                                    stmt.close();
                                    stmt = null;
                            }
                            if (con != null) {
                                    con.close();
                                    con = null;
                            }
                    } catch (SQLException e) {                        
                    }
            }
            out.close();
    }}

安卓代码:

public class MainActivity extends Activity{ 
private static final String ipAddress = "172.31.81.28";
private static final String portNumber = "8085";

protected TextView getText;
protected EditText inputName;
protected List<Student> students;


@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getText = (TextView) findViewById(R.id.select_output);
    inputName = (EditText) findViewById(R.id.name_input);
}

public void onClick(View v)
{   
    switch (v.getId())
    {
        case R.id.post_button:
        {
            //
            String responseString = "";
            try 
            {
                responseString = new HttpPostTask().execute("" + inputName.getText()).get(10, TimeUnit.SECONDS);
            } 
            catch (InterruptedException e) 
            {
                responseString = "#An Error Occured: InterruptedException";
                e.printStackTrace();
            } 
            catch (TimeoutException e) 
            {
                responseString = "#An Error Occured: TimeoutException";
                e.printStackTrace();
            }
            catch (ExecutionException e) 
            {
                responseString = "#An Error Occured: ExecutionException";
                e.printStackTrace();
            }

            if (responseString.startsWith("#"))
            {
                Toast.makeText(this,
                        responseString.substring(1), Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this,
                        responseString, Toast.LENGTH_SHORT).show();
            }

            break;
        }

        //code for getting data from DB
        case R.id.get_button:
        {
            String responseString = "";
            try 
            {
                responseString = new HttpGetTask().execute("").get(10, TimeUnit.SECONDS);
            } 
            catch (InterruptedException e) 
            {
                responseString = "#An Error Occured: InterruptedException";
                e.printStackTrace();
            } 
            catch (TimeoutException e) 
            {
                responseString = "#An Error Occured: TimeoutException";
                e.printStackTrace();
            }
            catch (ExecutionException e) 
            {
                responseString = "#An Error Occured: ExecutionException";
                e.printStackTrace();
            }

            if (responseString.startsWith("#"))
            {
                Toast.makeText(this,
                        responseString.substring(1), Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this,
                        "Connection Successful", Toast.LENGTH_SHORT).show();

                this.getText.setText(responseString);
                this.students = parseData(responseString, "\n", ":");

                int i = 0;
                for (Student student : students)
                {
                    ++i;
                    System.out.print("[" + i + "] " + student + "\n");
                }
            }

            break;
        }
        default:
        {
            /* Do Nothing */
        }
    }
}

private List<Student> parseData(String input, String caseDelimiter, String fieldDelimiter)
{
    String[] temp = input.split(caseDelimiter);

    LinkedList<Student> students = new LinkedList<Student>();
    for (int i = 0; i < temp.length; i++)
    {
        String[] tempStudent = temp[i].split(fieldDelimiter);
        students.add(new Student(Integer.parseInt(tempStudent[0]), tempStudent[1].trim()));
    }

    return students;
}

private class Student
{
    int id;
    String name;

    public Student(int id, String name)
    {
        this.id = id;
        this.name = name;
    }

    public String toString()
    {
        return "" + id + " - " + name;
    }
}

private class HttpPostTask extends AsyncTask<String, Integer, String>
{
    private static final String ipAddress = "172.31.81.28"; // *** UPDATE THIS ***
    private static final String portNumber = "8085"; // *** UPDATE THIS ***

    @Override
    protected String doInBackground(String... args)
    {
        String responseString = "An Unknown Error Occured";

        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpClient client = new DefaultHttpClient(params);

        String url = "http://" + ipAddress + ":" + portNumber + "/DB4";
        HttpPost request = new HttpPost(url);

        try
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "123"));
            nameValuePairs.add(new BasicNameValuePair("username", args[0]));

            request.setEntity(new UrlEncodedFormEntity(nameValuePairs));


            HttpResponse response = client.execute(request);
            HttpEntity resEntityGet = response.getEntity();
            if (resEntityGet != null) 
            {
                responseString = EntityUtils.toString(resEntityGet);
            }

        }
        catch (ClientProtocolException e) 
        {
            responseString = "#An Error Occured: ClientProtocolException";
            e.printStackTrace();
        }
        catch (IOException e) 
        {
            responseString = "#An Error Occured: IOException";
            e.printStackTrace();
        }

        return responseString;
    }
}

private class HttpGetTask extends AsyncTask<String, Integer, String>
{
    @Override
    protected String doInBackground(String... args)
    {
        String url = "http://172.31.81.28:8085/DB4";
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        String responseString = "";
        try 
        {

            HttpResponse response = client.execute(request);
            HttpEntity resEntityGet = response.getEntity();
            if (resEntityGet != null) 
            {
                responseString = EntityUtils.toString(resEntityGet);
            }

        }
        catch (Exception e) 
        {
            responseString = "#An Error Occured: UndeclaredException";
            e.printStackTrace();
        }

        return responseString;
    }
}   

}
4

1 回答 1

1

没关系,问题解决了。我使用了一个单独的 AsyncTask 类。

于 2013-03-13T17:48:03.683 回答