00.环境
jdk 1.8.0_25
mysql 5.6.24
eclipse 4.5.2
01.目录结构
不要忘记将mysql-connector-java-5.1.7-bin.jar右击Build Path。
02.准备数据
a.新建数据库my_first_batis
b.创建表
CREATE TABLE `user` (
`id` int(14) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL COMMENT '姓名',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '何方神圣',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
c.插入数据
insert into `user`(`name`,`birthday`,`sex`,`address`) values ('张三丰','1247-08-08','男','武当山');
insert into `user`(`name`,`birthday`,`sex`,`address`) values ('李四光','1889-10-26','男','科学院');
insert into `user`(`name`,`birthday`,`sex`,`address`) values ('王阳明','1472-10-31','男','贵州龙场');
insert into `user`(`name`,`birthday`,`sex`,`address`) values ('李清照','1084-07-07','女','山东济南');
insert into `user`(`name`,`birthday`,`sex`,`address`) values ('孔乙己','1850-06-06','男','浙江绍兴');
03.编写类文件
在src下新建包my_jdbc,新建类JdbcConnect
package my_jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author zhaoxiaopeng
* @version 创建时间:2016年11月3日 上午11:31:48
* 类说明 使用jdbc连接数据库,查询数据
*/
public class JdbcConnect {
public static void main(String[] args) {
// 数据库连接
Connection connection = null;
// 预编译的statement,使用预编译可以提高数据库的性能
PreparedStatement preparedStatement = null;
// 结果集
ResultSet resultSet = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 通过驱动管理类获取数据库链接
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_first_batis?characterEncoding=utf-8", "root", "root123");
// 定义sql语句 ?表示占位符
String sql = "select * from user where sex = ?";
// 获取预处理statement
preparedStatement = connection.prepareStatement(sql);
// 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
preparedStatement.setString(1, "男");
// 向数据库发出sql执行查询,查询出结果集
resultSet = preparedStatement.executeQuery();
// 遍历查询结果
while (resultSet.next()) {
System.out.println(resultSet.getString("name") + " " + resultSet.getString("address"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}