import java.sql.*;
import java.util.*;
class Student{
String sno;
String name;
public Student(String sno, String name) {
super();
this.sno = sno;
this.name = name;
}
@Override
public String toString() {
return "Student [sno=" + sno + ", name=" + name + "]";
}
}
public class TestJDBC {
public static void main(String[] args) {
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jbdc:mysql://localhost:3306/mydb?user=root&password=root&useUnicode=true&characterEncoding=UTF8";
con=DriverManager.getConnection(url);
System.out.println("连接成功!");
}catch(ClassNotFoundException e){
System.out.println("载入JDBC驱动类出错");
e.printStackTrace();
return;
}catch(SQLException e){
System.out.println("创建数据库连接出错");
e.printStackTrace();
return;
}
Statement stmt=null;
ResultSet rs=null;
List<Student> studentList=new ArrayList();
try {
String sql="Select * from student";
stmt=con.createStatement();
rs=stmt.executeQuery("mydatabase");
while(rs.next()) {
String sno=rs.getString("sno");
String name=rs.getString("name");
Student student=new Student(sno,name);
studentList.add(student);
}
}catch(SQLException e) {
System.out.println("查询数据库出错");
e.printStackTrace();
}finally {
try {
rs.close();
stmt.close();
con.close();
}catch(SQLException e) {
System.out.println("关闭资源出错");
e.printStackTrace();
rs=null;
stmt=null;
con=null;
}
}
for (Student student:studentList){
System.out.println(student);
}
}
}