Java连接MySQL数据库并插入数据涉及以下几个基础概念:
以下是一个简单的Java程序,演示如何使用JDBC连接MySQL数据库并插入数据:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, "John Doe");
pstmt.setString(2, "john.doe@example.com");
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
mysql-connector-java-8.0.23.jar
添加到项目的lib
目录,并在构建路径中包含该JAR文件。jdbc:mysql://localhost:3306/mydatabase
INSERT INTO users (name, email) VALUES (?, ?)
通过以上步骤和示例代码,您应该能够成功连接MySQL数据库并插入数据。如果遇到其他问题,请检查错误信息并进行相应的调试。
领取专属 10元无门槛券
手把手带您无忧上云