我在"如何""连接到我们的ASP.NET应用程序正在使用的预先累积的数据库。
所以,问题是我使用了sqljdbc4.jar库来尝试连接到我的数据库,在此期间我得到的只是异常,我似乎找不到有关它的解决方案。如果有人能够纠正我的代码或给我一些帮助,我将不胜感激。我似乎无法在任何地方找到解决方案。
下面是我在主要活动中的OnCreate块中调用的代码,其中我正在获取 os.NetworkOnMainThreadException
public void testDB() {
TextView tv = (TextView) this.findViewById(R.id.text_view);
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=CafeApp;user=Sunny;password=";
String result = "Database connection success\n";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ResultSetMetaData rsmd;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM inventory.inventory_name";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
rsmd = rs.getMetaData();
// Iterate through the data in the result set and display it.
while (rs.next()) {
// System.out.println(rs.getString(4) + " " + rs.getString(6));
result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
result += rsmd.getColumnName(3) + ": " + rs.getInt(3) + "\n";
}
tv.setText(result);
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
tv.setText(e.toString());
} finally {
if (rs != null) try {
rs.close();
} catch(Exception e) {
}
if (stmt != null) try {
stmt.close();
} catch(Exception e) {
}
if (con != null) try {
con.close();
} catch(Exception e) {
}
}}
答案 0 :(得分:0)
你必须使用AsyncTask ... 因为android不允许在它的主线程上进行任何网络任务。
将这个testDB()方法放在单独的线程上。
new Thread(new Runnable() {
@Override
public void run() {
testDB()
}
}).start();