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.在表中插入数据,以便显示
)
1 package com.test.an; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 9 10 public class TestCon1{ 11 public static void main(String[] args) 12 { 13 Connection con = null; 14 String sql; 15 PreparedStatement pre; 16 ResultSet rs; 17 18 try { 19 String driver="com.mysql.jdbc.Driver"; 20 Class.forName(driver); 21 22 String url="jdbc:mysql://localhost:3306/cui?useUnicode=true&characterEncoding=latin1";//utf-8也行 23 con = DriverManager.getConnection(url, "root", "123456"); 24 25 sql = "select _id,username,password from test1" ; 26 pre = con.prepareStatement(sql); 27 28 rs = pre.executeQuery(); 29 while(rs.next()){ 30 int id = rs.getInt(1); 31 String username = rs.getString(2); 32 String password = rs.getString(3); 33 34 System.out.println("id="+id+";username="+username+";password="+password); 35 } 36 con.close(); 37 } catch (SQLException e) { 38 e.printStackTrace(); 39 } catch (ClassNotFoundException e) { 40 e.printStackTrace(); 41 } 42 43 } 44 45 }
用力测试运行结果:
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