import java.sql.*;
public class InsertUser {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/user";
String username = "root";
String password = "your_password";
try {
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO user(username, password) VALUES(?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "root");
stmt.setString(2, "123");
int rows = stmt.executeUpdate();
System.out.println(rows + " rows inserted.");
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
注意将url
替换为您的MySQL连接字符串,username
替换为数据库用户的用户名,password
替换为对应的密码。执行该程序,将插入一个用户名为root,密码为123的记录到user
表中。