<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">一、向数据库中插入一条数据(增)</span>
</pre><pre name="code" class="java"><span style="font-size:18px;">public class Demo01 {
private static final String URL="jdbc:mysql://localhost:3306/ph_test";
private static final String USER="root";
private static final String PASSWORD="ok";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入姓名:");
String pname = input.nextLine();
System.out.print("请输入年龄:");
int age = input.nextInt();
System.out.print("请输入身高:");
int height = input.nextInt();
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.根据驱动管理器获取连接对象
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
//3.编写sql语句
String sql = "insert into person values(null,?,?,?)";
//4.创建预处理命令
PreparedStatement pst = conn.prepareStatement(sql);
//5.填充参数
pst.setString(1,pname );
pst.setInt(2, age);
pst.setInt(3, height);
//6.执行更新,返回一个整型变量,代表受影响函数
int count = pst.executeUpdate();
System.out.println(count>0? "添加成功":"添加失败");
//7.释放资源
pst.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}</span>