现在开发中都使用Hibernate来进行持久化实现,今天想到JDBC,所以就有了下边的小例子。
使用数据库MySQL5.0
MySQL驱动jar包:mysql-connector-java-5.1.3-rc-bin.jar
1.创建表
create table person
(
p_id int not null auto_increment,
p_name varchar(50),
p_sex varchar(10),
p_address varchar(100),
primary key(p_id)
)engine=myisam default charset=gbk
2.示例代码
/**
* JDBCTest.java
* @author xhmder
*/
package com.xhmder.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 使用JDBC访问MySQL
*/
public class JDBCTest
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
// 变量定义
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
// 加载MySQL驱动
try
{
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
//获取数据库连接(用户名root密码abcd)
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK","root", "abcd");
//获取表达式
stmt = conn.createStatement();
//执行数据插入
stmt.executeUpdate("insert into person(p_name,p_sex,p_address) values('xhmder','男','西安市')");
//执行数据检索
rs = stmt.executeQuery("select * from person");
//显示数据
while (rs.next())
{
System.out.println("******** p_id = " + rs.getString("p_id"));
System.out.println("******** p_name = " + rs.getString("p_name"));
System.out.println("******** p_sex = " + rs.getString("p_sex"));
System.out.println("******** p_address = " + rs.getString("p_address"));
}
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
//释放资源
if (conn != null)
{
try
{
conn.close();
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null)
{
try
{
stmt.close();
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (rs != null)
{
try
{
rs.close();
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}