package cn.it.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDemo {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root");
//写sql获取资源
String sql = "select * from user where username = ?";
//获取预处理
preparedStatement = connection.prepareStatement(sql);
//设置第一个参数从1开始
preparedStatement.setString(1, "老阴比");
//向数据库发出查询
resultSet = preparedStatement.executeQuery();
//遍历结果集
while(resultSet.next()){
System.out.println(resultSet.getString("id")+"..."+resultSet.getString("username"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭连接
try {
if (resultSet !=null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (preparedStatement !=null) {
preparedStatement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection !=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}