创建项目
创建一个Maven项目
不勾选模板。
在pom.xml文件中添加依赖:
数据库的连接:
package com.ethan.jdbc;
import java.sql.*;
/**
* @author Ethan
* @date 2020/1/15 - 16:08
*/
/*
解耦:降低程序间的依赖关系
实际开发中应该做到编译期不依赖,运行时才依赖。
解耦思路:
1.使用反射创建对象,而避免使用new关键字
2.读取配置文件来获取要创建的对象全限定类名
*/
public class JdbcDemo1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//注册驱动
//DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()); //如果驱动没有找到,将出现编译期错误
Class.forName("com.mysql.cj.jdbc.Driver"); //只有在运行时才可能抛出异常,但是驱动名称写死
//获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy?serverTimezone=GMT%2b8", "root", "6540");//注意如果不填写时区将出现The server time zone value '�й���ʱ��' is unrecognized
//获取操作数据库的预处理对象
PreparedStatement pstm = conn.prepareStatement("select * from account");
//执行sql,得到结果集
ResultSet rs = pstm.executeQuery();
//遍历结果集
while(rs.next()){
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
}
rs.close();
pstm.close();
conn.close();
}
}