java连接mysql数据库实现增删改查功能
时间: 2023-12-28 08:05:29 浏览: 123
以下是Java连接MySQL数据库实现增删改查功能的示例代码:
1. 连接数据库:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connect {
private static final String URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
```
2. 添加数据:
```java
public void tianjia(String id, String name, String score) {
try {
Connect ct = new Connect();
Connection conn = ct.getConnection();
String sql = "INSERT INTO student(id, name, score) VALUES(" + id + ", '" + name + "', " + score + ")";
conn.createStatement().executeUpdate(sql);
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
```
3. 修改数据:
```java
public void xiugai(String id, String name, String score) {
try {
Connect ct = new Connect();
Connection conn = ct.getConnection();
String sql = "UPDATE student SET name = '" + name + "', score = " + score + " WHERE id = " + id;
conn.createStatement().executeUpdate(sql);
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
```
4. 查询数据:
```java
public void chaxun() {
try {
Connect ct = new Connect();
Connection conn = ct.getConnection();
String sql = "SELECT * FROM student";
ResultSet rs = conn.createStatement().executeQuery(sql);
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String score = rs.getString("score");
System.out.println("ID: " + id + ", Name: " + name + ", Score: " + score);
}
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
```
阅读全文