我是編程新手,我正在嘗試使用NetBeans IDE創建一個小型Java swing應用程序,並且我設計了表單並創建了一個表格,我使用了以下代碼從表單數據插入到數據庫中,但我得到了許多錯誤,請幫我糾正這個代碼:如何將數據從文本框插入到mysql數據庫java-netbeans
import java.sql.*;
public class db
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
static final String USER="root";
static final String PASS="toor";
Connection conn = null;
Statement stmt = null;
static final String d_unit=jTextField2.getText();
static final String d_name=jTextField3.getText();
static final String d_dob=jDateChooser2.getText();
//static final String d_gender="gender";
static final String d_age=jTextField4.getText();
static final String d_doorno=jTextField5.getText();
static final String d_street=jTextField6.getText();
static final String d_vc=jTextField7.getText();
static final String d_district=jTextField8.getText();
static final String d_pin=jTextField9.getText();
static final String d_phone=jTextField10.getText();
static final String d_mail=jTextField11.getText();
static final String d_occupations=jTextField12.getText();
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) values('"+d_unit+"','"+d_name+"','"+d_dob+"','"+d_age+"','"+d_doorno+"','"+d_street+"','"+d_vc+"','"+d_district+"','"+d_pin+"','"+d_phone+"','"+d_mail+"','"+d_occupations+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e)
{ }
}
堆棧跟蹤,請 – Gerret
@Gerret我覺得這裏的問題是編譯時錯誤。 – Axel
您將所有值作爲'VARCHAR'插入。這些實際上是否定義爲數據庫中的變種?例如'doorno'或'age'看起來像整數。我也強烈建議使用'PreparedStatement'而不是'Statement'。請參閱[使用PreparedStatement](http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html) – dic19