感谢beansoft提供的《MyEclipse 6 Java 开发中文教程》,使我受益匪浅。
1、首先,当然要准备JDBC驱动啦
可以到mysql官方网站下载mysql-connector-java-5.1.6-bin.jar
2、
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(200) NOT NULL,
`password` varchar(20) NOT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=gbk;
/**
* @(#)JDBCTest.java
*
*
* @author keer2345
* @version 1.00 2008/8/11
*/
import java.sql.*;
public class JDBCTest {
public static void main(String[] args) {
// 1. 注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}
// 声明变量,使用,而后关闭
Connection conn = null; //数据库连接
Statement stmt = null; //数据库表达式
ResultSet rs = null; //结果集
try {
//2. 获取数据库的连接
conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK","root","");
//3. 获取表达式
stmt = conn.createStatement();
// 插入数据
stmt.executeUpdate("insert into Student (username, password, age) values ('张三','1234',20)");
//4. 执行SQL
rs = stmt.executeQuery("select * from Student");
//5. 现实结果集里面的数据
while(rs.next()) {
System.out.println("编号=" + rs.getInt(1));
System.out.println("姓名=" + rs.getString("username"));
System.out.println("密码=" + rs.getString("password"));
System.out.println("年龄=" + rs.getString("age"));
System.out.println("---------------");
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
try {
if(rs != null) {
rs.close();
}
if(sm != null) {
sm.close();
}
if(conn != null) {
conn.close();
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}