码迷,mamicode.com
首页 > 数据库 > 详细

jdbc

时间:2018-10-27 13:29:35      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:.sql   driver   int   tco   []   char   encoding   执行   查询参数   

import java.sql.*;
public class JdbcTest {
/**
* 1. //加载数据库驱动
* 2. //创建数据库连接
* 3. //创建statement
* 4. //设置sql语句
* 5. //设置查询参数
* 6. //执行查询,得到ResultSet
* 7. //解析结果集ResultSet
* 8. //释放资源
*/
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedSatement = null;
ResultSet resultSet = null;
try {
//1.加载数据库驱动
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=?";
//获取预处理statement
preparedSatement = connection.prepareStatement(sql);
//设置参数,第一个参数为第一个问号,第二个参数为设置参数的值
preparedSatement.setString(1, "王五");
//向数据库发出sql执行查询,查询出结果集。
resultSet = preparedSatement.executeQuery();
//遍历查询结果集
while (resultSet.next()) {
System.out.println(resultSet.getString("id") + ""
+ resultSet.getString("username"));

}

} catch (Exception e) {
e.printStackTrace();

}finally {
//释放资源
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedSatement!=null){
try {
preparedSatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

jdbc

标签:.sql   driver   int   tco   []   char   encoding   执行   查询参数   

原文地址:https://www.cnblogs.com/xkuankuan/p/9860685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!