android连接mysql查询表内记录_Android中Activity中访问数据库操作记录

public class MainActivity extends AppCompatActivity {

String UserName = "hhh";//用户名

String Password = "137006";//密码

Connection con = null;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

TextView viewById1 = (TextView) findViewById(R.id.tv_btn1);

TextView viewById2 = (TextView) findViewById(R.id.tv_btn2);

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);

viewById1.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

new Thread(new Runnable() {

@Override

public void run() {

try { // 加载驱动程序

Class.forName("com.mysql.jdbc.Driver");

//                            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Test1", UserName, Password);

con = DriverManager.getConnection("jdbc:mysql://192.168.1.97:3306/Test1?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false", UserName, Password);

} catch (ClassNotFoundException e) {

System.out.println("加载驱动程序出错");

} catch (SQLException sql) {

System.out.println("SQLException: " + sql.getMessage());

System.out.println("SQLState: " + sql.getSQLState());

System.out.println("Erro: " + sql.getErrorCode());

System.out.println("StackTrace: " + sql.getStackTrace());

System.out.println(sql.getMessage());

} catch (Exception e) {

System.out.println(e.getMessage());

}

}

}).start();

}

});

viewById2.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (con != null) {

try {

testConnection(con);

} catch (SQLException e) {

e.printStackTrace();

}

}

}

});

}

public void testConnection(Connection con) throws java.sql.SQLException {

try {

String sql = "SELECT * FROM GoodsInfo";//查询表名为“table_test”的所有内容

Statement stmt = con.createStatement();//创建Statement

ResultSet rs = stmt.executeQuery(sql);//ResultSet类似Cursor

while (rs.next()) {//ResultSet最初指向第一行

System.out.println(rs.getString("amount"));//输出第n行,列名为“test_id”的值

System.out.println(rs.getString("spec"));

}

rs.close();

stmt.close();

} catch (SQLException e) {

System.out.println(e.getMessage().toString());

} finally {

if (con != null)

try {

con.close();

} catch (SQLException e) {

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值