jdbc

  1. package cn.itcast.mybatis.jdbc;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. /**
  8. *
  9. * <p>Title: JdbcTest</p>
  10. * <p>Description:通过单独的jdbc程序,总结其中的问题 </p>
  11. * <p>Company: www.itcast.com</p>
  12. * @author 传智.燕青
  13. * @date 2015-4-22上午9:16:05
  14. * @version 1.0
  15. */
  16. public class JdbcTest {
  17. public static void main(String[] args) {
  18. //数据库连接
  19. Connection connection = null;
  20. //预编译的Statement,使用预编译的Statement提高数据库性能
  21. PreparedStatement preparedStatement = null;
  22. //结果 集
  23. ResultSet resultSet = null;
  24. try {
  25. //加载数据库驱动
  26. Class.forName("com.mysql.jdbc.Driver");
  27. //通过驱动管理类获取数据库链接
  28. connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "mysql");
  29. //定义sql语句 ?表示占位符
  30. String sql = "select * from user where username = ?";
  31. //获取预处理statement
  32. preparedStatement = connection.prepareStatement(sql);
  33. //设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
  34. preparedStatement.setString(1, "王五");
  35. //向数据库发出sql执行查询,查询出结果集
  36. resultSet = preparedStatement.executeQuery();
  37. //遍历查询结果集
  38. while(resultSet.next()){
  39. System.out.println(resultSet.getString("id")+" "+resultSet.getString("username"));
  40. }
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }finally{
  44. //释放资源
  45. if(resultSet!=null){
  46. try {
  47. resultSet.close();
  48. } catch (SQLException e) {
  49. // TODO Auto-generated catch block
  50. e.printStackTrace();
  51. }
  52. }
  53. if(preparedStatement!=null){
  54. try {
  55. preparedStatement.close();
  56. } catch (SQLException e) {
  57. // TODO Auto-generated catch block
  58. e.printStackTrace();
  59. }
  60. }
  61. if(connection!=null){
  62. try {
  63. connection.close();
  64. } catch (SQLException e) {
  65. // TODO Auto-generated catch block
  66. e.printStackTrace();
  67. }
  68. }
  69. }
  70. }
  71. }






附件列表

     

    posted @ 2017-02-06 00:43  stoneuu  阅读(201)  评论(0编辑  收藏  举报