怎么用java代码在mysql中插入数据
时间: 2023-12-03 20:43:09 浏览: 29
可以使用以下代码在MySQL中插入数据:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertDataExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO mytable (name, age) VALUES (?, ?)")) {
stmt.setString(1, "John");
stmt.setInt(2, 30);
int rowsInserted = stmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new row has been inserted.");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
```
其中,`url`是数据库的连接地址,`username`和`password`是数据库的用户名和密码。`PreparedStatement`用于执行带有参数的SQL语句,并且可以避免SQL注入的风险。在这个例子中,我们使用`setString`和`setInt`方法设置参数的值。最后,通过调用`executeUpdate`方法执行SQL语句并返回受影响的行数。