gpt4 book ai didi

java - JTable 的 SQLite 语法错误

转载 作者:行者123 更新时间:2023-12-02 04:14:33 25 4
gpt4 key购买 nike

您好,想使用 SQLite 数据库创建 JTable。数据应来自 SQLite 数据库并存储在其中。现在可以通过在文本字段中输入来添加新的详细信息。但是,我收到错误消息:“java.sql.SQLException:near”(“:语法错误”

出了什么问题?

    public class SQLite     {

public static DefaultTableModel model = new DefaultTableModel();
private static JTextField fieldID;
private static JTextField fieldName;
private static JTextField fieldAge;
private static JTextField fieldAddress;
private static JTextField fieldSalary;

public static void main( String args[] ) {

Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");

stmt = c.createStatement();

c.commit();

JFrame f = new JFrame();
f.setLayout(new GridLayout(5,1));
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

fieldID = new JTextField("ID");
fieldName = new JTextField("Name");
fieldAge = new JTextField("Age");
fieldAddress = new JTextField("Address");
fieldSalary = new JTextField("Salary");

String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (fieldID.getText(), feldName.getText(), Age.getText(), feldAddress.getText(), feldSalary.getText()";
stmt.executeUpdate(sql);

JTable table = new JTable(model);
f.add( new JScrollPane( table ) );

model.addColumn("id");
model.addColumn("name");
model.addColumn("age");
model.addColumn("address");
model.addColumn("salary");

ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");

model.addRow(new Object[] {id, name, age, address, salary});
}

/**JTextField feldID = new JTextField("ID");
JTextField feldName = new JTextField("Name");
JTextField feldAge = new JTextField("Age");
JTextField feldAddress = new JTextField("Address");
JTextField feldSalary = new JTextField("Salary");
**/

f.pack();
f.setVisible( true );

rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}

最佳答案

这是您的问题:

"VALUES (fieldID.getText(), feldName.getText(), Age.getText(), feldAddress.getText(), feldSalary.getText()";

它们被作为垃圾读取,而不是作为对 getter 的引用。

以下是您必须使用串联来替换它的内容。

“VALUES ("+fieldID.getText()+"、"+feldName.getText()+"、"+Age.getText()+"、"+feldAddress.getText()+"、"+feldSalary.getText()+");";

关于java - JTable 的 SQLite 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33462185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com