MySQL 篇- Java 连接 MySQL 数据库并实现数据交互
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MySQLAccess {
private Connection connect = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public void connectDB() {
try {
// 加载MySQL JDBC驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 设置数据库连接字符串,用户名和密码
String connectionString = "jdbc:mysql://localhost:3306/testdb?user=root&password=root";
// 建立连接
connect = DriverManager.getConnection(connectionString);
} catch (Exception e) {
e.printStackTrace();
}
}
public void insertData() {
try {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
preparedStatement = connect.prepareStatement(sql);
preparedStatement.setString(1, "John");
preparedStatement.setString(2, "john@example.com");
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void retrieveData() {
try {
String sql = "SELECT id, name, email FROM users";
preparedStatement = connect.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name") + ", Email: " + resultSet.getString("email"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MySQLAccess mySQLAccess = new MySQLAccess();
mySQLAccess.connectDB();
mySQLAccess.insertData();
mySQLAccess.retrieveData();
}
}
这段代码展示了如何使用Java连接MySQL数据库,并实现数据的插入和查询操作。首先加载JDBC驱动,然后建立连接,接着执行SQL语句进行数据的插入和查询。这是一个简单的例子,展示了如何在Java中使用JDBC操作数据库的基本步骤。
评论已关闭