引入:使用Handler进行处理,在更新数据的同时更新UI
注意:每次修改之后需要卸载虚拟机中的app再去安装就不会出现bug,不然的话有bug、
不联网的话访问不到mysql数据库中的信息。
需要采用自己的ip。注意不是localhost,不然就是访问手机自己的ip地址了,并不是电脑的,一定要注意。。。。
public class JDBCConnection {// 创建用于jdbc连接的公用的类
// 先定义几个用于连接的属性
// 1.驱动的名称private final static String driverName="com.mysql.jdbc.Driver";private final static String url="jdbc:mysql://128.45.69.88:3306/testdb?useSSL=false&serverTimezone=GMT";private final static String dbUser="root";private final static String dbPswd="root";// 静态的代码块static {try {Class.forName(driverName);} catch (ClassNotFoundException e) { e.printStackTrace();}}// 2.创建连接的对象public static Connection getConnection() throws SQLException {Connection conn=null;
conn= DriverManager.getConnection(url,dbUser,dbPswd);return conn;}// 3.关闭所有的资源对象public static void close(Connection conn, Statement state, ResultSet rs) throws SQLException {if(rs!=null) {
rs.close();}if(state!=null) {
state.close();}if(conn!=null) {
conn.close();}}}
public class MainActivity extends AppCompatActivity {protected static final Integer SUCCESS=1;protected static final Integer FAIL=0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//查询所有数据的线程new Thread(){@Overridepublic void run() {Connection conn = null;Statement stmt = null;ResultSet rs = null;//采用Message,注意不是new进行创建Message message = handler.obtainMessage();List list = new ArrayList<>();try {
conn = JDBCConnection.getConnection();// 3.编写sql并执行sql语句String sql = "select * from user";
stmt = conn.createStatement();// 4.遍历结果集
rs = stmt.executeQuery(sql);while (rs.next()) {Integer id = rs.getInt("id");String name = rs.getString("name");String sex = rs.getString("sex");System.out.println(id + "---" + name + "---" + sex + "---");
list.add(new User(id, name, sex));}//设置成功消息和数据
message.what = SUCCESS;
message.obj = list;//关闭资源JDBCConnection.close(conn, stmt, rs);} catch (Exception e) {
message.what = 0;
message.obj = FAIL;System.out.println("发生错误!" + e);}finally {//发生消息
handler.sendMessage(message);}}}.start();}
//处理主线程中的信息private Handler handler=new Handler(){@Overridepublic void handleMessage( Message msg) {if (msg.what==SUCCESS){TextView txtId1=findViewById(R.id.txtId1);TextView txtName1=findViewById(R.id.txtName1);TextView txtSex1=findViewById(R.id.txtSex1);TextView txtId2=findViewById(R.id.txtId2);TextView txtName2=findViewById(R.id.txtName2);TextView txtSex2=findViewById(R.id.txtSex2);List list=(List )msg.obj;
txtId2.setText(list.get(1).getId()+"");
txtName2.setText(list.get(1).getName()+"");
txtSex2.setText(list.get(1).getSex()+"");
txtId1.setText(list.get(0).getId()+"");
txtName1.setText(list.get(0).getName()+"");
txtSex1.setText(list.get(0).getSex()+"");Toast.makeText(MainActivity.this, "成功"+msg.obj, Toast.LENGTH_SHORT).show();}}
};}
