利用Java读取Mysql数据库中的数据,步骤如下:
1、利用Eclipse新建一个工程Test、
2、登录到Mysql,新建一个数据库caipiao
create database caipiao
3、新建表zhong,语句如下:
create table zhong
(
numid int primary key auto_increment,
qinum varchar(30),
num1 varchar(30),
num2 varchar(30),
num3 varchar(30),
num4 varchar(30),
num5 varchar(30),
num6 varchar(30),
num7 varchar(30)
)
4、查询几条语句
insert into zhong(qinum,num1,num2,num3,num4,num5,num6,num7) value('03001','10','11','12','13','26','28','11');
insert into zhong(qinum,num1,num2,num3,num4,num5,num6,num7) value('03002','4','9','19','20','21','26','12');
insert into zhong(qinum,num1,num2,num3,num4,num5,num6,num7) value('03003','1','7','10','23','28','32','16');
insert into zhong(qinum,num1,num2,num3,num4,num5,num6,num7) value('03004','4','6','7','10','13','25','3');
insert into zhong(qinum,num1,num2,num3,num4,num5,num6,num7) value('03005','4','6','15','17','30','31','16');
5、新建一个类MysqlDB,代码如下:
package com.yxl.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MysqlDB {
/**
* Mysql连接数据库例子
*/
public static void main(String[] args)
{
try
{
Connection conn;
Statement stmt;
ResultSet res;
//加载Connector/J驱动
//这一句也可写为:Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
//建立到MySQL的连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/caipiao", "root", "1");
//执行SQL语句
stmt = conn.createStatement();
res = stmt.executeQuery("select * from zhong");
//处理结果集
while (res.next())
{
String qinum = res.getString("qinum");
String num1 = res.getString("num1");
String num2 = res.getString("num2");
String num3 = res.getString("num3");
String num4 = res.getString("num4");
String num5 = res.getString("num5");
String num6 = res.getString("num6");
String num7 = res.getString("num7");
System.out.print(qinum+" ");
System.out.print(num1+" ");
System.out.print(num2+" ");
System.out.print(num3+" ");
System.out.print(num4+" ");
System.out.print(num5+" ");
System.out.print(num6+" ");
System.out.println(num7+" ");
}
res.close();
}
catch (Exception ex)
{
System.out.println("Error : " + ex.toString());
}
}
}
6、Run as Java Aplication,结果如下:
03001 10 11 12 13 26 28 11
03002 4 9 19 20 21 26 12
03003 1 7 10 23 28 32 16
03004 4 6 7 10 13 25 3
03005 4 6 15 17 30 31 16
备注:别忘了在工程中,将mysql-connector-java-5.1.17.jar包添加到build path.