1、创建项目
2、创建数据库
3、创建测试类
package com.xxg.javaee;
import java.sql.*;
/**
* @author xxg
* @version 1.0
* @date 2020/4/27 10:03
*/
public class TestJdbc {
public static void main(String[] args) throws SQLException {
Connection connection = null;
ResultSet rs = null;
Statement statement = null;
String url="jdbc:mysql://localhost:3306/jdbc?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
String username="root";
String password="123456";
try {
//1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取数据库连接
connection = DriverManager.getConnection(url, password, username);
//3、获取数据库对象
statement= connection.createStatement();
//4、编写sql语句
String sql="select * from jdbc.users";
//5、执行sql语句
rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getInt("id"));
System.out.println("name="+rs.getString("name"));
System.out.println("password="+rs.getString("password"));
System.out.println("email="+rs.getString("email"));
System.out.println("birthday="+rs.getDate("birthday"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//6、关闭数据库连接,先创后关
statement.close();
rs.close();
connection.close();
}
System.out.println("数据库操作成功");
}
}
注意事项:在获取数据库对象时,参数要一一对应不然会报一下错误: