JDBC连接Mysql数据库


import java.sql.*;

public class JDBCUtils {

    private static Connection con = null;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/whsxt?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
            String user = "root";
            String password = "123456";
            con = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("加载驱动失败");
            e.printStackTrace();
        }
    }
    public static  String sendSql(String sql) {
        Statement statement = null;
        try {
            statement = con.createStatement();
            if (sql.startsWith("select")) {
                ResultSet resultSet = statement.executeQuery(sql);
                return print(resultSet);
            } else {
                int i = statement.executeUpdate(sql);
                if (i>0){
                    return "ok";
                }else {
                    return "error";
                }
            }
        } catch (SQLException throwables) {
            System.out.println("sql异常");
            throwables.printStackTrace();
        }
        assert statement != null;
        close(con, statement);
        return  "error";
    }

    /**
     * 查询打印
     * @param resultSet
     * @return
     * @throws SQLException
     */
    private static String  print(ResultSet resultSet) throws SQLException {
        // 获取结果集中的元数据 可以得到列总数 找到列名
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        StringBuilder res = new StringBuilder();
        while (resultSet.next()){
            for (int i = 1; i < columnCount; i++) {
                res.append(metaData.getColumnName(i)).append(" ").append(resultSet.getString(i)).append("\n");
            }
        }
        return res.toString();
    }

    /**
     * 关闭资源
     * @param connection
     * @param statement
     */
    public static void close(Connection connection, Statement statement) {
        try {
            connection.close();
            statement.close();
        } catch (SQLException throwables) {
            System.out.println("释放资源失败");
            throwables.printStackTrace();
        }
    }
}
public static void main(String[] args) {
        String s = JDBCUtils.sendSql("select *from user");
        System.out.println(s);
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值