android开发 MyEclipse下测试连接MySQL数据库

1、首先要加载MySQL驱动包。

步骤:右击项目找到build path->configure build path->libraries——>add External JARs添加驱动包

2、写测试类:TestCon.java

(在此之前,首先必须

  1.在自己的电脑上Mysql下确定账户是"root",密码是"123456";

  2.进入账户,创建数据库cui;

  3.在数据库cui下面,创建表test1 包含_id(int 类型自动增加) username(String 类型)、password(String 类型);

  4.在表中插入数据,以便显示

 package com.test.an;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class TestCon1{
public static void main(String[] args)
{
Connection con = null;
String sql;
PreparedStatement pre;
ResultSet rs; try {
String driver="com.mysql.jdbc.Driver";
Class.forName(driver); String url="jdbc:mysql://localhost:3306/cui?useUnicode=true&characterEncoding=latin1";//utf-8也行
con = DriverManager.getConnection(url, "root", "123456"); sql = "select _id,username,password from test1" ;
pre = con.prepareStatement(sql); rs = pre.executeQuery();
while(rs.next()){
int id = rs.getInt(1);
String username = rs.getString(2);
String password = rs.getString(3); System.out.println("id="+id+";username="+username+";password="+password);
}
con.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} } }

  用力测试运行结果:

  id=1;username=ccc;password=123456
  id=2;username=xxx;password=654321
  id=3;username=ddd;password=123456
  id=4;username=ddf÷;password=yyt
  id=5;username=cuixiaodong;password=cxd
  id=6;username=vv;password=cxd

上一篇:monkeyrunner API接口文档内容


下一篇:gtest简短,简单易用