我正在尝试从Android应用程序连接到SQL服务器数据库。 连接有效,但由于表
java.sql.SQLException:无效的对象名称'dbo。名称'。
我发送到服务器的 SQL 代码是
stmt.execute("INSERT INTO [dbo].[Names] ([name]) VALUES ('Test')");
有什么想法吗?
编辑:
这是代码:
static String serverIp = "xxx.database.windows.net:1433";
static String serverDb = "xxxApp";
static String serverUserName = "xxx";
static String serverPassword = "xxx";
Connection con;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckLogin checkLogin = new CheckLogin();
checkLogin.execute("");
}
public class CheckLogin extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(String r) {
}
@Override
protected String doInBackground(String... params) {
try {
con = connectionclass(serverUserName, serverPassword, serverDb, serverIp);
if (con == null) {
z = "Check Internet Access";
} else {
Statement stmt = con.createStatement();
stmt.execute("INSERT INTO [dbo].[Names] ([name]) VALUES ('Test')");
String x = ""; // DEBUG point
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
return z;
}
@SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server) {
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://" + server + ";database=" + database + ";user=" + user + ";password=" + password + ";encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
connection = DriverManager.getConnection(ConnectionURL);
} catch (SQLException se) {
Log.e("error here 1 : ", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("error here 2 : ", e.getMessage());
} catch (Exception e) {
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
SQL 语句失败,因为您没有为 jTDS 使用正确的连接 URL 格式,因此您实际上没有连接到由字符串变量 serverDb
指定的数据库。
您正在尝试使用名为 database
的连接 URL 参数,而 jTDS 无法识别该参数:
String serverDb = "myDb";
String connUrl = "jdbc:jtds:sqlserver://localhost:49242;database=" + serverDb;
try (Connection conn = DriverManager.getConnection(connUrl, myUid, myPwd)) {
System.out.println(conn.getCatalog()); // prints: master
} catch (Exception e) {
e.printStackTrace(System.err);
}
相反,您应该使用文档中描述的server:port/database
格式
String serverDb = "myDb";
String connUrl = "jdbc:jtds:sqlserver://localhost:49242/" + serverDb;
try (Connection conn = DriverManager.getConnection(connUrl, myUid, myPwd)) {
System.out.println(conn.getCatalog()); // prints: myDb
} catch (Exception e) {
e.printStackTrace(System.err);
}