[英]Connecting Java to MS Access using JCreator
I'm still new to this. 我还是新手。 But, I'm having a problem inserting data in mt database. 但是,我在mt数据库中插入数据时遇到问题。 I think there's a lot of mistakes going on in my script 我认为我的剧本中出现了很多错误
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Student extends JFrame
{
//Component's name
private JLabel lblName,lblAge,lblGrade;
private JTextField txtName, txtAge,txtGrade;
private JButton btnAdd;
String c;
String d;
String e;
public void Student()
{
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "Information";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "abcd";
Container container = getContentPane();
container.setLayout(new FlowLayout());
lblName=new JLabel("Name: ");
container.add(lblName);
txtName=new JTextField(30);
container.add(txtName);
lblAge=new JLabel("Age: ");
container.add(lblAge);
txtAge=new JTextField(2);
container.add(txtAge);
lblGrade=new JLabel("Grade: ");
container.add(lblGrade);
txtGrade=new JTextField(1);
container.add(txtGrade);
btnAdd=new JButton("Add");
container.add(btnAdd);
btnAdd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
c=txtName.getText();
d=txtAge.getText();
e=txtGrade.getText();
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement statement = conn.prepareStatement("INSERT INTO Information ('StudentName', 'StudentAge','Grade') VALUES ('"+c+"', '"+d+"', '"+e+"'')");
statement.executeQuery();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
setSize(300,300);
setVisible(true);
}
public static void main(String[]args)
{
Student application = new Student();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
So, can anyone help me fix what is wrong here? 那么,任何人都可以帮我解决这里的错误吗? Please see the screenshot below for the output. 请参阅下面的屏幕截图了解输出。
1-You don't need t use ''
to the name of your column 'StudentName'
, if you need that then use use ``
instead to ''
1 - 您不需要使用''
列名'StudentName'
,如果您需要,那么使用``
代替''
2-You have a problem in your query here : 2 - 您的查询中存在问题:
...('"+c+"', '"+d+"', '"+e+"'')
You set two ''
in the end, and this make a problem. 你最后设置了两个''
,这就产生了问题。
Why you dont use ? 你为什么不用? like this : 像这样 :
PreparedStatement statement =
conn.prepareStatement("INSERT INTO Information (StudentName, StudentAge, Grade) VALUES (?, ?, ?)");
statement.setString(1, c);
statement.setString(2, d);
statement.setString(3, e);
statement.executeQuery();
You can learn more here about Prepared Statement doc 您可以在此处了解有关Prepared Statement doc的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.