操作数据库

mac 安装mysql

1
brew install mysql

启动

1
mysql.service start

jdbc

环境配置

jdbc 是java 本身操作数据库的一个方式

但是我们需要下载一个驱动

image-20250422134831111

Maven Repository: mysql » mysql-connector-java (mvnrepository.com)

选择一个版本

进行下载

下载之后会有一个jar 包,然后放到项目中

image-20250422135035342

这边是通过创建了一个lib 目录,然后放进去的

只有需要加载到项目中

image-20250422135156364

环境到这,就安装成功了

操作mysql

模拟了一个获取数据的过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.example.demo;

import com.sun.tools.javac.Main;

import javax.xml.transform.Result;
import java.sql.*;

public class GetNews {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver"); // mysql 驱动
String url="jdbc:mysql://localhost:3306/demo"; // demo 是数据库的名字
String user="root";
String password="";
String sql="select * from news";
try {
Connection conn= DriverManager.getConnection(url,user,password);
if (conn.isValid(3)){
System.out.println("连接成功");
}else{
System.out.println("连接失败");
}
Statement stmt=conn.createStatement();
stmt.executeQuery(sql);
ResultSet rs=stmt.executeQuery(sql);
while (rs.next()){
String id=rs.getString("id");
String title=rs.getString("new");
System.out.println("id:"+id+" new:"+title);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}


操作数据库
https://tsy244.github.io/2025/04/22/javaee/操作数据库/
Author
August Rosenberg
Posted on
April 22, 2025
Licensed under