理论上讲,android不应该直接连接数据库的,但是处于业务需要,且自己局域网使用,不存在泄漏问题,所以就尝试了android直接连接mysql数据库
首先,需要网络连接权限,这就不说了,然后添加mysql连接依赖包:
compile 'mysql:mysql-connector-java:5.1.18'
最后下面这段代码即可连接成功,记得在异步线程执行。
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();
}
}
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!