下载MySQL JDBC Connector 3.0.17并将其添加到您的 android 项目构建路径中。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import android.app.Activity;
导入android.os.Bundle;导入 android.widget.TextView;
public class MysqlSample01Activity extends Activity {
private static final String url = "jdbc:mysql://<server>:<port>/<database>";
private static final String user = "<username>";
private static final String pass = "<password>";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testDB();
}
public void testDB() {
TextView tv = (TextView)this.findViewById(R.id.text_view);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
/* System.out.println("Database connection success"); */
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from table_name");
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
}
tv.setText(result);
}
catch(Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
}
}