Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example;
- import java.io.PrintWriter;
- import java.sql.*;
- public class JDBCDemo {
- public static void main(String[] args) throws ClassNotFoundException, SQLException {
- // 1. 要连接的数据库url
- String url = "jdbc:mysql://localhost:3306/jdbcStudy";
- // 连接数据库要使用的用户名
- String username = "root";
- // 连接数据库要使用的密码
- String password = "8887447235";
- // 2. 加载驱动
- //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 不推荐使用这种方式
- Class.forName("com.mysql.jdbc.Driver"); // 使用反射机制加载
- // 3. 获取与数据库的连接
- Connection con = DriverManager.getConnection(url, username, password);
- // 4. 获取向数据库发送sql语句的statement
- Statement st = con.createStatement();
- // sql语句
- String sql = "select id,name,password,email,birthday from users";
- // 5. 向数据发送sql语句
- ResultSet set = st.executeQuery(sql);
- // 6. 取出结果集数据
- while (set.next()){
- System.out.println("id=" + set.getObject("id"));
- System.out.println("name=" + set.getObject("name"));
- System.out.println("password=" + set.getObject("password"));
- System.out.println("email=" + set.getObject("email"));
- System.out.println("birthday=" + set.getObject("birthday"));
- }
- // 7. 关闭连接释放资源
- set.close();
- st.close();
- con.close();
- }
- }
Add Comment
Please, Sign In to add comment