android直接连接mysql数据库

理论上讲,android不应该直接连接数据库的,但是处于业务需要,且自己局域网使用,不存在泄漏问题,所以就尝试了android直接连接mysql数据库
首先,需要网络连接权限,这就不说了,然后添加mysql连接依赖包:

1
compile 'mysql:mysql-connector-java:5.1.18'

最后下面这段代码即可连接成功,记得在异步线程执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private void connect() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://192.168.1.1:3306/database_name";
connection = (Connection) DriverManager.getConnection(url, "username", "password");
Statement statement = (Statement) connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select * from table_name";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
Log.i("TAG", resultSet.getString("content"));
}
} catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

蔡小木 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!