CREATE DATABASE mydatabase; USE mydatabase; CREATE TABLE customers ( customerID varchar(8) primary key, name varchar(40) default NULL, phone varchar(16) default NULL ); INSERT INTO customers VALUES ('ADDIFK01','Frank Addinsell', '(718) 555-3911'); INSERT INTO customers VALUES ('ALBIBB01','Bob Albinoni', '(213) 555-7566');package homework7_二_1_20221548; import java.sql.*; import javax.swing.JOptionPane; public class DemoInsert { public static void main(String args[]){ String url="jdbc:mysql://127.0.0.1:3306/mydatabase"; String user="root",pwd=""; Connection con; Statement sql; ResultSet rs; try {Class.forName("com.mysql.jdbc.Driver"); }catch (ClassNotFoundException e){ System.out.println("test"+e); } try { con = DriverManager.getConnection(url, user, pwd); sql = con.createStatement(); // String mysql = "INSERT INTO customers VALUES('ALBRDE01','DAVE Albrechtsberger','(508) 555-1216)"; String mysql = "INSERT INTO customers VALUES('ALBRDE01','DAVE Albrechtsberger','(508) 555-1216') and ('ALKAJM01','Jim Alkan','(832) 555-5617')"; int k = sql.executeUpdate(mysql); if (k == 1) JOptionPane.showMessageDialog(null, "插入记录成功", "成功", JOptionPane.PLAIN_MESSAGE); con.close(); }catch (SQLException ee){ JOptionPane.showMessageDialog(null, "插入记录失败", "失败", JOptionPane.ERROR_MESSAGE); } } }为什么显示插入数据失败?
时间: 2024-03-11 07:45:30 浏览: 94
sql2008sql查询语句大全[借鉴].pdf
在您提供的代码中,SQL语句存在问题。INSERT INTO语句只能插入一条记录,而您的SQL语句中包含了两条记录。因此,您需要将SQL语句更改为:
String mysql = "INSERT INTO customers VALUES('ALBRDE01','DAVE Albrechtsberger','(508) 555-1216'), ('ALKAJM01','Jim Alkan','(832) 555-5617')";
这样就可以插入两条记录了。如果还是无法插入数据,请检查数据库连接是否正常,以及表结构是否正确。
阅读全文