因為項目需要Android直連服務(wù)端mysql數(shù)據(jù)庫,特寫下筆記
1.連接數(shù)據(jù)庫驅(qū)動依賴:compile'mysql:mysql-connector-java:5.1.18'
2.代碼如下
Connection connection =null;
//數(shù)據(jù)實體類
SouSuoCiData data;
//實體類list
gjclist=newArrayList();
try{
//加載驅(qū)動
Class.forName("com.mysql.jdbc.Driver").newInstance();
//數(shù)據(jù)庫ip地址/端口/數(shù)據(jù)庫名
String url ="jdbc:mysql://192.168.0.103:3306/test";
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //root是我這個數(shù)據(jù)庫的賬號和悦,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");
//解析查詢的數(shù)據(jù)
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();
}
}