因为项目需要Android直连服务端mysql数据库,特写下笔记
1.连接数据库驱动依赖:compile'mysql:mysql-connector-java:5.1.18'
2.代码如下
Connection connection =null;
//数据实体类
SouSuoCiData data;
//实体类list
gjclist=newArrayList();
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver").newInstance();
//数据库ip地址/端口/数据库名
String url ="jdbc:mysql://192.168.0.103:3306/test";
//root是我这个数据库的账号,123456是密码
connection = (Connection) DriverManager.getConnection(url,"root","123456");
Statement statement = (Statement) connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
//写查询语句
ResultSet resultSet = statement.executeQuery("select * from gjcbg");
//解析查询的数据
while(resultSet.next()) {
data=newSouSuoCiData();
//Log.i("TAG", "rs="+resultSet.toString());
data.setTime(resultSet.getString("sj"));
data.setJh(resultSet.getString("jh"));
data.setDy(resultSet.getString("dy"));
data.setGjc(resultSet.getString("gjc"));
data.setSsc(resultSet.getString("ssc"));
data.setZx(resultSet.getInt("zx"));
data.setDj(resultSet.getInt("dj"));
// Log.i("TAG", "data="+data.toString());
ssclist.add(data);
}
}catch(ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}finally{
try{
if(connection !=null) {
connection.close();
}
}catch(SQLException e) {
e.printStackTrace();
}
}