我试图将值从 JTextField 中的用户输入插入到表中。代码运行时出现错误:
您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法
谁能帮我解决这个问题?谢谢!
这是我的代码。
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
class InputRoute
{
JTextField text1;
JTextField text2;
JTextField text3;
String c;
Float d;
public void inputRoute()
{
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "YarraTram";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "abc123";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement statement = conn.prepareStatement("INSERT INTO ('route', 'price') VALUES ('"+c+"', '"+d+"')");
statement.executeQuery();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void createAndShowGUI()
{
final JFrame frame = new JFrame("Yarra Tram Route Finder(New Route)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JLabel label1 = new JLabel("From: ");
JLabel label2 = new JLabel("To: ");
JLabel label3 = new JLabel("Price: ");
text1 = new JTextField(20);
text2 = new JTextField(20);
text3 = new JTextField(20);
JButton button1 = new JButton("Add");
JButton button2 = new JButton("Close");
frame.add(label1, BorderLayout.WEST);
frame.add(text1, BorderLayout.EAST);
frame.add(label2, BorderLayout.WEST);
frame.add(text2, BorderLayout.EAST);
frame.add(label3, BorderLayout.WEST);
frame.add(text3, BorderLayout.EAST);
frame.add(button1);
frame.add(button2);
button2.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String a = text1.getText();
String b = text2.getText();
d = Float.parseFloat(text3.getText());
c = a + " - " + b;
inputRoute();
}
});
button2.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
});
frame.setSize( 500,120 );
frame.setLocationRelativeTo( null );
frame.pack();
frame.setVisible(true);
}
}
这是我的 MySQL 表
CREATE TABLE `route` (
`rid` int(11) NOT NULL AUTO_INCREMENT,
`route` varchar(100) ,
`price` decimal(5,2) ,
PRIMARY KEY (`rid`)
)