3.11

可以从数据库查数据

public class MainActivity extends AppCompatActivity {
private Button button,buttonInsert;
private TextView textView;
private static final int TEST_USER_SELECT = 1;
int i =0;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
String user;
switch (msg.what){
case TEST_USER_SELECT:
Test test = (Test) msg.obj;
user = test.getName();
System.out.println("***********");
System.out.println("***********");
System.out.println("user:"+user);
textView.setText(user);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.bt_send);
textView = (TextView) findViewById(R.id.tv_response);
}

@Override
protected void onStart() {
super.onStart();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//执行查询操作
//通多点击buttoni自增长查询对应id的name
if (i<=3){//因为数据库我就添加了三个数据条数,所以进行判断使其可以循环查询
i++;
}
else{
i=1;
}
//连接数据库进行操作需要在主线程操作
new Thread(new Runnable() {
@Override
public void run() {
Connection conn = null;
conn =(Connection) com.example.mysqlconnection1.DBOpenHelper.getConn();
String sql = "select name from test_one where id='"+i+"'";
Statement st;
try {
st = (Statement) conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
//因为查出来的数据试剂盒的形式,所以我们新建一个javabean存储
Test test = new Test();
test.setName(rs.getString(1));
Message msg = new Message();
msg.what =TEST_USER_SELECT;
msg.obj = test;
handler.sendMessage(msg);
}
st.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}).start();

}
});
buttonInsert = (Button) findViewById(R.id.bt_insert);
buttonInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 连接数据库进行操作需要在主线程操作
new Thread(new Runnable() {
@Override
public void run() {
Connection conn = null;
conn =(Connection) com.example.mysqlconnection1.DBOpenHelper.getConn();
String name = "NewName"; // 新数据的名称
String sql = "insert into test_one(name) values('"+name+"')";
Statement st;
try {
st = (Statement) conn.createStatement();
int rowAffected = st.executeUpdate(sql);
if (rowAffected > 0) {
// 插入成功,您可以选择显示一个Toast或者执行其他UI更新操作
}
st.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}).start();
}
});

}
}
posted @ 2024-03-11 23:30  涨涨涨张  阅读(5)  评论(0编辑  收藏  举报