Android连接SQL Server无法插入数据,无报错求技术支持
I'm developing a simple CRUD app using Android with SQL Server. When I click the add button, the record isn't saved to the database, but there are no error messages displayed. I've been troubleshooting this for two days without luck, please help!
Here's my code:
EditText ed1,ed2; Button b1,b2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1 = findViewById(R.id.title); ed2 = findViewById(R.id.course); b1 = findViewById(R.id.btn1); b2 = findViewById(R.id.v1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { insert(); } }); } public void insert() { try { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); String connectionUrl = "jdbc:jtds:sqlserver://KOBINATH-PC; databaseName=skill; user=sa; password=admin123"; Connection con = DriverManager.getConnection(connectionUrl); PreparedStatement pst; String title = ed1.getText().toString(); String description = ed2.getText().toString(); pst = con.prepareStatement("insert into course(coursename,fee)values(?,?)"); pst.setString(1, title); pst.setString(2, description); pst.executeUpdate(); Toast.makeText(this, "Success", Toast.LENGTH_LONG).show(); ed1.setText(""); ed2.setText(""); ed1.requestFocus(); } catch (Exception ex) { Toast.makeText(this, "Record Fail", Toast.LENGTH_LONG).show(); } }
Hey there, I feel your pain—spending two days stuck on a silent failure is the worst. Let's break this down step by step to find what's going wrong:
1. First, fix your exception handling to see what's actually breaking
Right now, your catch block only shows a generic "Record Fail" toast, but it's hiding the actual error message that would tell you exactly what's wrong. Let's modify it to log and display the real exception:
catch (Exception ex) { Log.e("InsertError", "Failed to insert record", ex); // This will show full error in Logcat Toast.makeText(this, "Record Fail: " + ex.getMessage(), Toast.LENGTH_LONG).show(); }
Check Logcat (Android Studio's Logcat tab) for the full stack trace—this is the single most important step here.
2. Stop using StrictMode for network/db operations on the main thread
While StrictMode.permitAll() lets you run database calls on the main thread, this is a terrible practice and can cause silent failures, freezes, or even crashes. Android blocks network/database operations on the main thread for good reason—they're slow and can lock up your UI.
Instead, use AsyncTask (for older Android versions) or Java Executors to run the insert in a background thread. Here's a quick AsyncTask example for your insert method:
private class InsertTask extends AsyncTask<Void, Void, Boolean> { private String title; private String fee; public InsertTask(String title, String fee) { this.title = title; this.fee = fee; } @Override protected Boolean doInBackground(Void... voids) { try { String connectionUrl = "jdbc:jtds:sqlserver://KOBINATH-PC; databaseName=skill; user=sa; password=admin123"; Connection con = DriverManager.getConnection(connectionUrl); PreparedStatement pst = con.prepareStatement("insert into course(coursename,fee)values(?,?)"); pst.setString(1, title); pst.setString(2, fee); int rowsAffected = pst.executeUpdate(); con.close(); return rowsAffected > 0; } catch (Exception ex) { Log.e("InsertTask", "Error inserting", ex); return false; } } @Override protected void onPostExecute(Boolean success) { if (success) { Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(); ed1.setText(""); ed2.setText(""); ed1.requestFocus(); } else { Toast.makeText(MainActivity.this, "Record Fail", Toast.LENGTH_LONG).show(); } } }
Then call it from your onClick:
b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String title = ed1.getText().toString(); String fee = ed2.getText().toString(); new InsertTask(title, fee).execute(); } });
3. Verify your SQL Server connection details
- Hostname issue: If you're testing on an Android emulator,
KOBINATH-PCwon't resolve to your local PC. Use10.0.2.2instead (this is the emulator's alias for the host machine's localhost). If testing on a physical device, use your PC's actual local IP address (e.g.,192.168.1.100) and make sure both devices are on the same Wi-Fi network. - Credentials & database name: Double-check that
sahas the correct password (admin123), that theskilldatabase exists, and that thesauser has write permissions to thecoursetable.
4. Check your database table structure
Your insert statement uses coursename and fee columns. Ask yourself:
- Is
feea string type (likeVARCHAR)? If it's a numeric type (e.g.,INT,DECIMAL), usingsetString(2, description)will cause a type mismatch error (which your old catch block hid). Iffeeis numeric, parse the input to a number first:// Example if fee is INT int feeValue = Integer.parseInt(ed2.getText().toString()); pst.setInt(2, feeValue); - Does the
coursetable have any other required columns that aren't being set? If there's a non-null column without a default value, the insert will fail silently (again, your old catch block would hide this).
5. Check if the insert is actually executing
Add a log for the number of rows affected by executeUpdate():
int rowsAffected = pst.executeUpdate(); Log.d("InsertResult", "Rows affected: " + rowsAffected);
If this returns 0, that means the SQL ran but no rows were inserted—usually a sign of a mismatch between your parameters and the table's constraints.
Once you implement the first step (fixing exception handling), you'll have a clear idea of what's going wrong. Let me know what the error message says if you're still stuck!
内容的提问来源于stack exchange,提问作者vijay kumar

