使用JDBC连接MySQL数据库,标准流程

import jdbc.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");

        //获取连接Connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "12345678");
        //得到执行sequel语句的对象Statement
        Statement stmt = conn.createStatement();
        //执行sql语句,并返回结果
        stmt.executeUpdate("insert into log value ('wcy',6,'234561')");
        ResultSet rs = stmt.executeQuery("select id,name,password from log");

        List<User> userList = new ArrayList<>();

        //处理结果
        while(rs.next()){
            User u = new User();
            u.setId(rs.getInt("id"));
            u.setName(rs.getString("name"));
            u.setPassword(rs.getString("password"));
            userList.add(u);

        }

        //关闭资源
        stmt.close();
        conn.close();

        for(User i:userList){
            i.print();
        }
    }
}
posted @ 2019-09-30 19:41  zju_cxl  阅读(101)  评论(0)    收藏  举报