第一个JDBC程序
运行环境:
MySql 5.7
mysql-connector-java-5.1.47
idea-2019.3.3
-
创建测试数据库
-
创建一个普通的java项目
-
导入数据库驱动
- 创建一个lib文件夹,将jar包粘贴至lib
- 加入library
-
编写测试代码
- 加载驱动
Class.forName("com.mysql.jdbc.Driver");
- 写登录信息
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true"; String name = "root"; String pwd = "123456";
(1) mysql默认端口是3306。
(2) URL = “协议://主机地址:端口号/数据库名?参数1&参数2&参数3”。这个协议不同的数据库是不一样的,Oracle数据库好像是jdbc:oracle什么什么的。
(3) useSSL=true 有的人说useSSL值要为false,可能和版本有关系。我这个环境是useSSL=true是能正常运行的,好像还有啥时区问题,我也没遇见,碰到的话会补充的。
- 连接数据库(获得数据库对象)
Connection connection = DriverManager.getConnection(url, name, pwd);
- connection是一个数据库对象
- 获取数据库对象
Statement statement = connection.createStatement();
- 通过数据库对象执行sql语句
String sql = "SELECT * FROM `users`";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("name"));
System.out.println("pwd="+resultSet.getObject("pwd"));
System.out.println("birthday="+resultSet.getObject("birthday"));
System.out.println("-------------------------");
}
- 释放连接
resultSet.close();
statement.close();
connection.close();
将这些步骤都和使用SQLyog操作数据库的步骤一 一 对应,能便于理解和记忆代码。
-
加载驱动就是打开SQLyog
-
填写登录信息就相当于这个步骤
-
然后就连接数据库,获取数据库对象就相当于在SQLyog中选中要使用的数据库。
-
然后就是写sql执行语句
-
关闭连接,退出。
完整代码
import java.sql.*;
public class jdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String name = "root";
String password = "123456";
//3.连接成功,返回数据库对象
// DriverManager---驱动管理 connection--代表数据库
Connection connection = DriverManager.getConnection(url, name, password);
//4.执行SQL对象
Statement statement = connection.createStatement();
//5.执行SQL
String sql = "SELECT * FROM `users`";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("name"));
System.out.println("pwd="+resultSet.getObject("pwd"));
System.out.println("birthday="+resultSet.getObject("birthday"));
System.out.println("-------------------------");
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}