|
1.1 流程
java连接mysql大致需要这六步:
导入驱动包:这里我使用的是mysql-connector-java-8.0.17.jar(点击下载),这个包连接mysql5.6,5.7,8.0版本都没问题。
Class.forName("com.mysql.cj.jdbc.Driver");
url和账户名密码
JDBC连接串:jdbc:mysql://<地址>:<端口>/<数据库>
获取连接:DriverManager.getConnection(url, user, password);
执行sql的Statement对象:connection.createStatement();
执行SQL
释放连接
1.2 一个测试连接的java程序JdbcFirstDemo.java - package com.peng.less01;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class JdbcFirstDemo {
- public static void main(String[] args) throws ClassNotFoundException, SQLException {
- // 1.导入驱动类
- Class.forName("com.mysql.cj.jdbc.Driver");
- // 2.用户信息和url
- String url = "jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false";
- String user = "root";
- String password = "12345678";
- // 3.获取连接
- Connection conn = DriverManager.getConnection(url, user, password);
- // 4.执行SQL的对象
- Statement sta = conn.createStatement();
- // 5.执行SQL
- String sql = "select * from account";
- ResultSet rs = sta.executeQuery(sql);
- while (rs.next()){
- System.out.println("id= " + rs.getObject("id"));
- System.out.println("name= " + rs.getObject("name"));
- System.out.println("money= " + rs.getObject("money"));
- System.out.println("=========================================");
- }
- // 6.释放连接
- rs.close();
- sta.close();
- conn.close();
- }
- }
复制代码
|
|