当前位置:Gxlcms > 数据库问题 > jdbc

jdbc

时间:2021-07-01 10:21:17 帮助过:4人阅读

;
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   执行   查询参数   

人气教程排行