2017-02-12 153 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 - 你不需要T選用''你列'StudentName'的名稱,如果你需要再使用使用``而不是''

2,你有一個問題,你的在這裏查詢:

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

你到底設置兩個'',這使問題。

爲什麼你不使用?像這樣:

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