Java Android:HttpPost-尝试将用户输入的数据插入服务器上的SQL表中

Java Android:HttpPost-尝试将用户输入的数据插入服务器上的SQL表中,java,android,sql,sql-server,http-post,Java,Android,Sql,Sql Server,Http Post,我正在做一个android项目,我试图获取用户在EditText框中输入的文本,并将其添加到我服务器上的SQL表中。我认为问题在于没有正确的SQL查询,但我不确定我必须添加什么(对于SQL,我一无所知):S 当我在手机上运行此应用程序时,它似乎承认我输入了一些内容并将其传递到数据库(没有出现错误或异常),但实际上没有向数据库表添加任何内容 任何关于我哪里出错的想法都将不胜感激 JDBC服务器代码: public class DBServlet4 extends HttpServlet {

我正在做一个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();
    }}
Android代码:

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;
    }
}   

}
public类MainActivity扩展活动{
专用静态最终字符串ipAddress=“172.31.81.28”;
私有静态最终字符串portNumber=“8085”;
受保护的文本视图获取文本;
受保护的编辑文本输入名;
受保护名单学生;
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getText=(TextView)findViewById(R.id.select\u输出);
inputName=(EditText)findViewById(R.id.name\u输入);
}
公共void onClick(视图v)
{   
开关(v.getId())
{
案例R.id.post_按钮:
{
//
字符串responseString=“”;
尝试
{
responseString=new-HttpPostTask().execute(“+inputName.getText()).get(10,TimeUnit.SECONDS);
} 
捕捉(中断异常e)
{
responseString=“#发生错误:InterruptedException”;
e、 printStackTrace();
} 
捕获(超时异常e)
{
responseString=“#发生错误:TimeoutException”;
e、 printStackTrace();
}
捕获(执行例外)
{
responseString=“#发生错误:ExecutionException”;
e、 printStackTrace();
}
if(responseString.startsWith(“#”)
{
Toast.makeText(这个,
responseString.substring(1),Toast.LENGTH_SHORT.show();
}
其他的
{
Toast.makeText(这个,
响应,吐司。长度(短)。显示();
}
打破
}
//从数据库获取数据的代码
案例R.id.get_按钮:
{
字符串responseString=“”;
尝试
{
responseString=new-HttpGetTask().execute(“”).get(10,TimeUnit.SECONDS);
} 
捕捉(中断异常e)
{
responseString=“#发生错误:InterruptedException”;
e、 printStackTrace();
} 
捕获(超时异常e)
{
responseString=“#发生错误:TimeoutException”;
e、 printStackTrace();
}
捕获(执行例外)
{
responseString=“#发生错误:ExecutionException”;
e、 printStackTrace();
}
if(responseString.startsWith(“#”)
{
Toast.makeText(这个,
responseString.substring(1),Toast.LENGTH_SHORT.show();
}
其他的
{
Toast.makeText(这个,
“连接成功”,Toast.LENGTH_SHORT.show();
this.getText.setText(responseString);
this.students=parseData(responseString,“\n”,“:”;
int i=0;
用于(学生:学生)
{
++一,;
系统输出打印(“[”+i+“]”“+student+”\n”);
}
}
打破
}
违约:
{
/*无所事事*/
}
}
}
私有列表解析数据(字符串输入、字符串大小写分隔符、字符串字段分隔符)
{
字符串[]temp=input.split(caseDelimiter);
LinkedList学生=新建LinkedList();
对于(int i=0;i