Insert data into mysql using jdbc through android.

2019-09-22 02:36发布

问题:

protected String doInBackground(String... params) {
    try {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Connection conn = (Connection) DriverManager.getConnection(DB_Url, user_name, pass);
        if (conn == null) {
            msg = "Connection failed";

        } else {
            String query = "INSERT INTO mytable (data) VALUES('" + input_data + "')";
            Statement statement = conn.createStatement();

        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return msg;
}

this Class is for background process to insert data into MySQL through Android application, with the help of JDBC library every thing fine but the method createStatement() is unresolvable

This is the error message:

enter image description here

回答1:

Every thing is fine with your program you need just to complete it so, you should to execute your statement like this :

Statement statement = conn.createStatement();
int res = statement.executeUpdate(query);

Then if you want to check your query is insert with success or not, you can check like this :

int res = statement.executeUpdate(query);
if(res>0){
    //success
}else{
    //failed
}

So if the statement execute with success it will return an int great than one it dippend of your query else it will return 0 and that mean your query is failed.

Note

Using statement can cause a syntax error or an sql injection, so to avoid that you can use PrepapredStatement it is more secure and more helpful, so instead your way you can use this :

String query = "INSERT INTO mytable (data) VALUES(?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, input_data);

int res = preparedStatement.executeUpdate();

Good luck.