标签归档:odbc

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();
                }
            }
        }

    }
}

继续阅读