• java 简单的控制台程序实现mysql数据读取


    新建控制台应用程序Application client project

    引入jar包

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;

    引入mysql连接就jar包

    项目  properties—>build path –> add  extend jar

    mysql-connector-java-5.1.38-bin.jar

    Connection connection = null;
            // 预编译的Statement,使用预编译的Statement提高数据库性能
            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", "123456");
                // 定义sql语句 ?表示占位符
                String sql = "select * from users where name = ?";
                // 获取预处理statement
                preparedStatement = connection.prepareStatement(sql);
                // 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
                preparedStatement.setString(1, "用户孤傲苍狼");
                // 向数据库发出sql执行查询,查询出结果集
                resultSet = preparedStatement.executeQuery();
                // 遍历查询结果集
                while (resultSet.next()) {
                    System.out.println(resultSet.getString("id") + "  "
                            + resultSet.getString("name"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 释放资源
                if (resultSet != null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (preparedStatement != null) {
                    try {
                        preparedStatement.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
    
            }
  • 相关阅读:
    括号序列的dp问题模型
    粉刷匠
    木棍加工
    物流运输
    最短路图
    DP基础(线性DP)总结
    离散化
    树链剖分
    NOIP2016 “西湖边超萌小松鼠” 模拟赛
    NOI导刊 2009 提高二
  • 原文地址:https://www.cnblogs.com/ilooking/p/5159082.html
Copyright © 2020-2023  润新知