android+studio+sql
时间: 2023-12-07 11:39:09 浏览: 119
为了在Android Studio中读取SQL Server数据库中的数据,需要创建一个线程来获取SQL Server中的数据。在配置文件Androidmanifest.xml中添加`<uses-permission android:name="android.permission.INTERNET"/>`,否则无法进行网络连接。
以下是一个简单的示例代码,演示如何在Android Studio中连接SQL Server数据库并获取数据:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private static final String DB_URL = "jdbc:jtds:sqlserver://your_server_name:your_port/your_database_name";
private static final String USER = "your_username";
private static final String PASS = "your_password";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "SELECT * FROM your_table_name";
rs = stmt.executeQuery(sql);
while (rs.next()) {
String column1 = rs.getString("column1");
int column2 = rs.getInt("column2");
// do something with the data
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
```
请注意,上述代码仅为示例,实际情况可能需要根据具体的数据库和表结构进行修改。
阅读全文