教学中的JDBC都是在IDE(如eclipse中)加入驱动jar包的,这次试试用命令行的方式来访问JDBC!
环境:Windows7 + java8 + mysql 5.5 + mysql-connector-java-5.1.7-bin.jar
我的工作目录下文件如下:
这是我mysql中创建的数据库和表以及里面的数据(这个根据具体情况来):
下面谈谈代码,Person类主要是对表进行映射,是表里数据的容器。JDBCTest类就是重头戏了,使用JDBC的基本步骤都在里面。
Person.java:
package org.rr.jdbctest;
public class Person {
private int pid;
private int age;
private String name;
private String sex;
public Person(int pid, int age, String name, String sex) {
this.pid = pid;
this.age = age;
this.name = name;
this.sex = sex;
}
public int getId() {
return pid;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
@Override
public String toString() {
return "ID: " + getId() + " , Age: " + getAge() + ", " +
"Name: " + getName() + ", Sex:" + getSex() + ".";
}
}
JDBCTest.java:
import java.sql.*;
import org.rr.jdbctest.Person;
import java.util.*;
public class JDBCTest {
public static void main(String[] args) throws SQLException, ClassNotFoundException{
// Load Driver
Class.forName("com.mysql.jdbc.Driver");
// Build Connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123");
// Create Statement
Statement stat = conn.createStatement();
// Execute Sql
ResultSet rs = stat.executeQuery("select * from person");
List<Person> list = new ArrayList<>();
while (rs.next()) {
Person person = new Person(rs.getInt("pid"), rs.getInt("age"),
rs.getString("name"),rs.getString("sex"));
list.add(person);
}
rs.close();
stat.close();
conn.close();
for (Person p : list) {
System.out.println(p.toString());
}
}
}
cmd到你的工作目录下命令行执行:
set classpath=%classpath%;mysql-connector-java-5.1.7-bin.jar
javac -d . Person.java
javac -d . JDBCTest.java
java JDBCTest
运行截图: