注意:,我可以删除数据库并可以通过外壳创建表,但是当我在Android Studio中运行查询以通过权限被拒绝错误创建表时。
连接可以成功建立数据库。
我正在使用Microsoft Azure的Stander S0层(免费试用)
这是我的代码:
公共类MainActivity扩展了AppCompatActivity {
Button add;
TextView errorlbl;
EditText name, address, pincode;
Connection connect;
Context context;
PreparedStatement preparedStatement;
Statement st;
String ipaddress, db, username, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.btnadd);
errorlbl = (TextView) findViewById(R.id.lblerror);
name = (EditText) findViewById(R.id.txtname);
address = (EditText) findViewById(R.id.txtaddress);
pincode = (EditText) findViewById(R.id.txtpincode);
connect = ConnectionHelper();
if (connect != null) {
System.out.println ("Connet is NOT NULL");
// Drop previous table of same name if one exists.
Statement statement = null;
try {
statement = connect.createStatement ();
} catch (SQLException e) {
e.printStackTrace ();
}
try {
statement.execute ("DROP TABLE IF EXISTS studentRecord;");
System.out.println ("Finished dropping table (if existed).");
} catch (SQLException e) {
e.printStackTrace ();
}
// Create table.
try {
statement.execute ("CREATE TABLE studentRecord (Name VARCHAR(50), Address VARCHAR(50), Pincode INTEGER PRIMARY KEY);");
System.out.println ("Created table.");
} catch (SQLException e) {
Log.e ("Database not created", e.getMessage ());
e.printStackTrace ();
}
}
else {
System.out.println ("Connet is NULL");
}
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
st = connect.createStatement();
preparedStatement = connect
.prepareStatement("insert into studentRecord (Name,Address,Pincode) values ('"
+ name.getText().toString()
+ "','"
+ address.getText().toString()
+ "','"
+ pincode.getText().toString() + "')");
preparedStatement.executeUpdate();
errorlbl.setText("Data Added successfully");
} catch (SQLException e) {
errorlbl.setText(e.getMessage().toString());
}
}
});
}
@SuppressLint("NewApi")
public Connection ConnectionHelper(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll ()
.build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName ("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://andridserver.... this link work fine";
connection = DriverManager.getConnection (ConnectionURL);
System.out.println ("Connection successful");
}
catch (SQLException se){
Log.e ("error 1: ", se.getMessage ());
}
catch (ClassNotFoundException cne){
Log.e ("error 2 :", cne.getMessage ());
}
catch (Exception e){
Log.e ("error 3 :", e.getMessage ());
}
return connection;
}
}