mysql jdbc驱动下载地址: http://pan.baidu.com/share/link?shareid=22738&uk=2366527449
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MysqlConnection {
public Connection getConnection(){
Connection con=null;
/**
* 注册驱动
*/
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("驱动载入失败!!!");
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("驱动载入失败!!!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("驱动载入失败!!!");
}
/**
* 连接Mysql数据库
* person是数据库名
*/
try {
con= DriverManager.getConnection("jdbc:mysql://localhost/person?user=root&password=");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
public class Student {
private int id;
private String name;
private int age;
public String toString(){
return "学生编号: "+this.getId()+"学生姓名: "+this.getName()+"学生年龄: "+this.getAge();
}
public Student(int id,String name,int age){
this.setAge(age);
this.setId(id);
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
public class Test {
public static void main(String[] args) {
MysqlConnection mysqlConnection=new MysqlConnection();
Connection con=mysqlConnection.getConnection();
PreparedStatement pst=null;
ResultSet rs=null;
List<Student> list=new ArrayList<Student>();
try {
pst=con.prepareStatement("select * from `student`");
rs=pst.executeQuery();
while(rs.next()){
Student student=new Student(rs.getInt(1),rs.getString(2), rs.getInt(3));
list.add(student);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < list.size(); i++) {
Student student=(Student)list.get(i);
System.out.println(student.toString());
}
}
}
CREATE DATABASE `person`
CHARACTER SET 'gb2312'
COLLATE 'gb2312_chinese_ci';
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` int(11) NOT NULL DEFAULT '21',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=gb2312;