java 连接 mysql 并使用 prepareStatement 查询数据库

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.sql.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {

        Connection conn = null;
        User user = null;
        Gson gson = new Gson();

        try {
            # JDK6 之前的版本需要加载驱动
            # new com.mysql.jdbc.Driver();

            # 连接数据库
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname?" +
                    "useSSL=false&useUnicode=true&characterEncoding=UTF8", "root", "root");

            # 使用 prepareStatement 查询数据库
            PreparedStatement preStatement = conn.prepareStatement("select * from tables");
            ResultSet res = preStatement.executeQuery();

            List<User> users = new ArrayList<User>();
            while (res.next()) {
                user = new User();
                user.setId(Integer.parseInt(res.getString("id")));
                user.setUser(res.getString("user"));
                users.add(user);
            }
            # 导出为 json
            String strJson = gson.toJson(users);
            System.out.println(strJson);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

# 用到的类
public class User {

    private int id;
    private String user;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", user='" + user + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

2 + 7 =