使用Jdbc接口访问数据库

2018-08-20  本文已影响5人  空谷幽心

查询

直接扔代码。

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

/**
 * JdbcDemo
 */
public class JdbcDemo {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/taotao_db", "taotao",
                "hiwwt_123")) {
            PreparedStatement stmt = conn.prepareStatement("select id from user_accounts");
            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {
                System.out.println("got id=" + resultSet.getInt("id"));
            }
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读