写一个java连接mysql的例子,并实现判断是否连接成功,对数据库增删改查,给出maven依赖配置,代码越详细越好
时间: 2024-03-13 21:45:44 浏览: 53
好的,下面是一个简单的Java连接MySQL的例子,包括判断连接是否成功和增删改查操作:
1. Maven依赖配置:
```xml
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
```
2. 连接MySQL数据库并判断是否连接成功:
```java
import java.sql.*;
public class MySQLDemo {
public static void main(String[] args) {
Connection conn = null;
try {
// 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立连接
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
// 判断是否连接成功
if (conn != null) {
System.out.println("连接成功!");
} else {
System.out.println("连接失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
3. 对数据库进行增删改查操作:
```java
import java.sql.*;
public class MySQLDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立连接
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
// 插入数据
String sql = "INSERT INTO user(name, age, sex) VALUES (?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, "张三");
ps.setInt(2, 18);
ps.setString(3, "男");
int result = ps.executeUpdate();
if (result > 0) {
System.out.println("插入成功!");
} else {
System.out.println("插入失败!");
}
// 更新数据
sql = "UPDATE user SET age = ? WHERE name = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, 20);
ps.setString(2, "张三");
result = ps.executeUpdate();
if (result > 0) {
System.out.println("更新成功!");
} else {
System.out.println("更新失败!");
}
// 查询数据
sql = "SELECT * FROM user WHERE age > ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, 18);
rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
String sex = rs.getString("sex");
System.out.println("姓名:" + name + ",年龄:" + age + ",性别:" + sex);
}
// 删除数据
sql = "DELETE FROM user WHERE name = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "张三");
result = ps.executeUpdate();
if (result > 0) {
System.out.println("删除成功!");
} else {
System.out.println("删除失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
以上是一个简单的Java连接MySQL的例子,代码中注释有详细的说明,希望能够帮助你!
阅读全文