java简单jdbc查询操作
所采用的mysql的数据库驱动版本:5.0.8
mysql-connector-java-5.0.8-bin.jar
程序结构图:
表结构:
创表sql:
Create Table |
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(200) DEFAULT NULL, `password` varchar(32) DEFAULT NULL, `sex` char(1) DEFAULT NULL, `birthday` date DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 |
package com.itheima.mydatis.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class JdbcTest {
// 定义sql
private static String sql = "SELECT * FROM users t WHERE t.username LIKE ?";
public static void main(String[] args) throws SQLException {
// 连接对象
Connection connection = null;
// 预编译对象 PreparedStatement
PreparedStatement preparedStatement = null;
// 结果集
ResultSet resultSet = null;
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接对象
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatisdb", "root", "123");
// 获取preparedStatement
preparedStatement = connection.prepareStatement(sql);
// 为preparedStatement对象的sql中的占位符设置参数
preparedStatement.setString(1, "%张%");
// 执行sql语句,并返回结果集到resultSet中
resultSet = preparedStatement.executeQuery();
// 遍历结果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
Date birthday = resultSet.getDate("birthday");
System.out.println(id + "--" + username + "--" + birthday);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
}
}
}
执行结果: