2017-02-12 16 views
1

私はまだこれに慣れていません。しかし、mtデータベースにデータを挿入する際に問題があります。私は私のスクリプトで起こっJCreatorを使用してJavaをMS Accessに接続する

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); 
} 

} 

だから、誰も私がここで間違っているものを修正することができます多くのミスだと思いますか?出力については、下記のスクリーンショットをご覧ください。

enter image description here

+0

あなたがエラーを入れてくださいすることができ、私は画像を見ることができない、ここで多くを学ぶことができます –

答えて

0

1-あなたはその後、

2 - あなたは''

に代わりに使用 ``を使用することをあなたに問題を持っている必要がある場合は、tはあなたのコラム 'StudentName'の名前に ''を使う必要はありません。ここでクエリ:

...('"+c+"', '"+d+"', '"+e+"'') 

最後に''を2つ設定すると問題になります。

なぜあなたは使用しませんか?このように:

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(); 

あなたはおよそPrepared Statement doc

関連する問題