public class MainActivity extends AppCompatActivity {
String UserName = "hhh"; // username
String Password = "137006"; // password
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 "; // query table named "table_test" all the contents
Statement stmt = con.createStatement (); // creation of Statement
ResultSet rs = stmt.executeQuery (SQL); // ResultSet similar Cursor
while (rs.next ()) {// <code> ResultSet </ code> initially points to the first row
System.out.println (rs.getString ( "amount") ); // the n-th row, a column named "test_id" value
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) {
}
}
}
}