首先在在MySQL数据库中创建数据库和表,比如执行如下脚本:
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
`id` int(2) NOT NULL auto_increment,
`name` char(4) default NULL,
`gender` char(2) default NULL,
`birth` date default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
创建了个person表。。。。。。
下面是JDBC的工具类:
package com.jdbc.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public final class JdbcUtil {
private static String url ="jdbc:mysql://localhost:3306/mysqltest?&useUnicode=true&characterEncoding=UTF-8";
private static String user = "root";
private static String password = "123456";
private JdbcUtil(){}
//注册驱动
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
//抛出异常,提示出错
throw new ExceptionInInitializerError();
}
}
//建立连接
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url,user,password);
}
//释放资源
public static void free(Connection conn,Statement stmt,ResultSet rs){
try{
if(rs!=null)
rs.close();
} catch(SQLException e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}finally{
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
JDBC的测试类:
package com.jdbc.model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCModel {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
temple();
}
static void temple() throws SQLException{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//利用工具类注册驱动,建立与mysql的连接
conn = JdbcUtil.getConnection();
//创建连接语句
stmt = conn.createStatement();
String insertsql = "insert into person(name,gender,birth) values('老朱','男','1986-1-1')";
String querysql = "select * from person";
//执行插入语句
stmt.executeUpdate(insertsql);
//执行查询语句
rs = stmt.executeQuery(querysql);
//处理结果
while(rs.next()){
System.out.println("-----------------------------------");
System.out.println("记录"+rs.getString("id")+
"\t姓名:"+rs.getString("name")+"\n"+
"\t性别:"+rs.getString("gender")+"\n"+
"\t出生年月:"+rs.getString("birth"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
//释放资源
JdbcUtil.free(conn, stmt, rs);
}
}
}
哦了。。。。。。。。。。。