我无法使用textfield在表中插入值

时间:2015-10-22 15:21:29

标签: java sql text insert textfield

我需要创建一个程序,在该程序中可以使用Java中的textfield插入值。

  

数据库连接...
  bt无法使用JTextfield插入值....需要帮助..
  显示错误..
  java.sql.SQLException:参数索引超出范围(1>参数个数,为0)。

package youtubetest;
import java.sql.*;
import java.awt.event.*;
import javax.swing.*;

public class YouTubeTest extends JFrame{
private static final String USERNAME = "root";
private static final String PASSWORD = "****";
private static final String CONN_STRING = "jdbc:mysql://localhost:3306/youtube";
Connection conn;
PreparedStatement stmt;

JButton b1,b2;
JTextField t1,t2;
JLabel l1,l2;
String Fname;
String Lname;

public YouTubeTest()
{
    setSize(600,600);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setLayout(null);

    add(t1 = new JTextField(30));
    t1.setBounds(10,10,200,50);
    add(t2 = new JTextField(30));
    t2.setBounds(10, 100, 200, 50);

    add(l1 = new JLabel("First Name : "));
    l1.setBounds(220, 10, 200, 50);
    add(l2 = new JLabel("Last Name : "));
    l2.setBounds(220, 100, 200, 50);

    add(b1 = new JButton("Submit"));
    b1.setBounds(10, 400, 60, 60);
    add(b2 = new JButton("Clear"));
    b2.setBounds(100, 400, 60, 60);

    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
        System.out.println("Database Connected Succesfully ..... ");


        stmt = conn.prepareStatement("Insert into user(Fname,Lname) values('"+Fname+"','"+Lname+"')");

    }catch(Exception e){
        e.printStackTrace();
    }

    b1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent ae){
                try{

            Fname = t1.getText();
            Lname = t2.getText();
            stmt.setString(1, Fname);
            stmt.setString(2, Lname);
            stmt.executeUpdate();
        }catch(Exception e){
        e.printStackTrace();
    }}
    });  

    b2.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
           t1.setText("");
           t2.setText("");
        }
    });

    addWindowListener(new WindowAdapter() 
    {
        public void windowClosing(WindowEvent we)
        {
            try{
                stmt.close();
                conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    });  

    setVisible(true);
}

public static void main(String[] args)throws Exception {


    new YouTubeTest();




}
};

0 个答案:

没有答案