2015-09-05 132 views
-2

代碼:我想從用戶數據,並插入到數據庫(SQL)

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 

import javax.swing.JOptionPane; 

public class NewTry { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     String dep,namee,cnic,cell; 
     int id; 
      id=Integer.parseInt(txtTeacherId.getText()); 
      namee=txtTeacherName.getText(); 
      dep=cmbDepName.getSelectedItem().toString(); 
      cnic=txtTeacherCnicNo.getText(); 
      cell=txtTeacherCellNo.getText(); 
      try 
      { 
//    try 
//     { 
//     // create a mysql database connection 
//     String myDriver = "org.gjt.mm.mysql.Driver"; 
//     String myUrl = "jdbc:mysql://localhost/test"; 
//     Class.forName(myDriver); 
//     Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", ""); 
//      

       //Class.forname("sun.jdbc.odbc.JdbcOdbcDriver"); 
       Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/test", "root", ""); 
       // JOptionPane.showMessageDialog(null,n); 
       String insertSql = "INSERT INTO Teacher VALUES (?, ?, ?, ?, ?)"; 
       PreparedStatement pInsertTeacher = conn.prepareStatement(insertSql); 
      // pInsertTeacher=conn.prepareStatement("INSERT INTO TEACHER VALUES(?,?,?,?,?)"); 
       pInsertTeacher.setInt(1,id); 
       pInsertTeacher.setString(2,namee); 
       pInsertTeacher.setString(3,dep); 
       pInsertTeacher.setString(4,cnic); 
       pInsertTeacher.setString(5,cell); 

       pInsertTeacher.executeUpdate(); 

       //preparedStmt.execute(); 
       System.out.println("Data inserted Successfully Check your SQL table"); 
      } 
      catch(ClassNotFoundException e) 
      { 
       System.out.println(e.toString()); 
      } catch (SQLException e) { 
       JOptionPane.showMessageDialog(null, "Record Already Inserted...."); 
      } 
    } 
} 

我想從用戶接受輸入並保存到SQL數據庫。但我無法做出我想要的代碼。 有錯誤是運行收到此代碼:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
txtTeacherId cannot be resolved 
txtTeacherName cannot be resolved 
cmbDepName cannot be resolved 
txtTeacherCnicNo cannot be resolved 
txtTeacherCellNo cannot be resolved 
at NewTry.main(NewTry.java:17) 
+0

你的用戶交互形式在哪裏? – subash

+0

您沒有聲明任何「教師」字段。 – itwasntme

+1

你對錯誤信息有什麼瞭解? – babon

回答

0

您的代碼基本上沒有編譯能。 On line

id=Integer.parseInt(txtTeacherId.getText()); 
namee=txtTeacherName.getText(); 
dep=cmbDepName.getSelectedItem().toString(); 
cnic=txtTeacherCnicNo.getText(); 
cell=txtTeacherCellNo.getText(); 

您正在使用尚未聲明的變量。嘗試

Console c = System.console(); 
id=Integer.parseInt(c.readLine("Insert teacher ID: ")); 
namee=c.readLine("Insert teacher name: "); 
dep=c.readLine("Insert teacher department: "); 
cnic=c.readLine("Insert teacher cnic: "); 
cell=c.readLine("Insert teacher cell: "); 

改爲。當然,如果你想使用用戶界面來定義數據,你應該選擇Java AWT,Java SWING或Java FX教程。

相關問題