idea连接mysql数据库进行增删改查
时间: 2023-09-14 16:10:12 浏览: 106
ssm-crud.rar_DEMO_forestql4_java_ssm增删改查demo_框架
首先需要在项目中引入 mysql-connector-java 的依赖,然后在代码中进行数据库的连接和操作,下面是一个简单的示例:
1. 连接数据库
```java
import java.sql.*;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
```
2. 插入数据
```java
public class InsertDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBUtil.getConnection();
String sql = "INSERT INTO student(name, age, sex) VALUES (?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "张三");
pstmt.setInt(2, 20);
pstmt.setString(3, "男");
int result = pstmt.executeUpdate();
if (result > 0) {
System.out.println("插入成功!");
} else {
System.out.println("插入失败!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, pstmt, null);
}
}
}
```
3. 更新数据
```java
public class UpdateDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBUtil.getConnection();
String sql = "UPDATE student SET age = ? WHERE name = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 21);
pstmt.setString(2, "张三");
int result = pstmt.executeUpdate();
if (result > 0) {
System.out.println("更新成功!");
} else {
System.out.println("更新失败!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, pstmt, null);
}
}
}
```
4. 查询数据
```java
public class QueryDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "SELECT * FROM student WHERE name = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "张三");
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("姓名:" + rs.getString("name"));
System.out.println("年龄:" + rs.getInt("age"));
System.out.println("性别:" + rs.getString("sex"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, pstmt, rs);
}
}
}
```
需要注意的是,一定要在使用完数据库连接等资源后进行关闭,否则会出现资源泄漏问题。在上述示例中,我们使用了一个工具类 DBUtil 来进行资源的关闭操作。
阅读全文