将 Java 中的 TextField 中的值插入到数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15748027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:43:45  来源:igfitidea点击:

Inserting values from my TextField in Java into a database

javaswingjtextfieldsql-insertactionevent

提问by Ivan ?eli?anin

I'm a newbie here and I would have one question that I'm having hard times getting an answer to. I need to set up a program in Java that could enable the user to insert values into a database based on what they type in the TextField. Here are the 3 classes that I've created:

我是这里的新手,我有一个问题很难得到答案。我需要在 Java 中设置一个程序,使用户能够根据他们在 TextField 中键入的内容将值插入到数据库中。这是我创建的 3 个类:

public class Odabrani{

    public int id;
    String ime;
    String prezime;

        public Odabrani(int id, String ime, String prezime){

            this.id=id;
            this.ime=ime;
            this.prezime=prezime;


        }
}


import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;



    public class MySQL{ 
        public static Connection connect() throws InstantiationException, ClassNotFoundException, IllegalAccessException, SQLException{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/prodavnica", "root", "");
            return conn;
        }
    public static void Obrisi(int id) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
        Connection conn = connect();
        Statement st = (Statement) conn.createStatement();
        st.execute("delete from prodavac where id = " + id);
        conn.close();
    }


    public static List<Prodavac> GetProdavci() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    Connection conn = connect();
    Statement st = (Statement) conn.createStatement();
    st.executeQuery("select * from prodavac");
    ResultSet rs = st.getResultSet();
    List<Prodavac> pr = new ArrayList<Prodavac>();
    while(rs.next()){
        pr.add(new Prodavac(rs.getInt(1),rs.getString(2),rs.getString(3)));
        //String ime = rs.getString(2);

    }
    conn.close();
        return pr;

        }

    public static void Dodaj(String ime, String prezime) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
        Connection conn = connect();
        PreparedStatement pst = conn.prepareStatement("insert into prodavac (id, ime, prezime) values (null,' ,' ) + ime, prezime;");
        conn.close();
    }


    }



import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.List;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author v
 */
**public class Main** {
       static TextField unos;
       public static Prodavac odabrani_prodavac;
       public static JComboBox c;
       public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{
        Frame f = new Frame("Biblioteka");
        f.setSize(300, 300);
        f.setLocation(300, 300);
        f.setVisible(true);
        f.setLayout(new FlowLayout()); 
        c = new JComboBox();
        List l = new List();
        unos = new TextField(20);
        f.add(unos);

        unos.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    MySQL.Dodaj(odabrani_prodavac.ime, odabrani_prodavac.prezime);
                } catch (InstantiationException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });




        Button b = new Button("obrisi");
        b.addActionListener(new ActionListener() {

               @Override
               public void actionPerformed(ActionEvent e) {
                   if(odabrani_prodavac!=null)
                   try {
                       MySQL.Obrisi(odabrani_prodavac.id);
                       c.removeAllItems();
                       java.util.List<Prodavac> prlist = MySQL.GetProdavci();
                        for(Prodavac p: prlist)
                            c.addItem(p);

                   } catch (InstantiationException ex) {
                       Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                   } catch (IllegalAccessException ex) {
                       Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                   } catch (ClassNotFoundException ex) {
                       Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                   } catch (SQLException ex) {
                       Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                   }
               }
           });

        java.util.List<Prodavac> prlist = MySQL.GetProdavci();
        for(Prodavac p: prlist)
               c.addItem(p);
        f.add(c);
        f.add(b);
        c.addItemListener(new ItemListener() {

               @Override
               public void itemStateChanged(ItemEvent e) {
                   if(e.getStateChange()==ItemEvent.SELECTED){
                    Prodavac p = (Prodavac)e.getItem();
                    odabrani_prodavac = p;
                    JOptionPane.showMessageDialog(null, "Odabrali ste: " + p.toString());
                   }
               }
           });





       }
}

Now, if you pay attention to this you can see that both the delete() and gettAll() methods work perfect but it's the insert method(s) that bother me. How do I play around this code in question so the text that user types in gets stored into a database. Please advise. Thank You! Ivan

现在,如果您注意这一点,您会发现 delete() 和 gettAll() 方法都可以完美运行,但困扰我的是 insert 方法。我如何处理有问题的这段代码,以便用户键入的文本存储到数据库中。请指教。谢谢!伊万

采纳答案by prasanth

Change your insert statement to

将插入语句更改为

PreparedStatement pst = conn.prepareStatement("insert into prodavac (id, ime, prezime) values (null,'"+ime+"','"+prezime+"'" ); 

回答by Reimeus

PreparedStatementprovides placeholder characters to protect against SQL Injectionattacks as well as handle as the insertion of any quotes that may be required. Also if idis an auto incrementfield, you can omit this from the SQL:

PreparedStatement提供占位符字符以防止SQL 注入攻击以及处理可能需要的任何引号的插入。此外,如果id自动增量字段,您可以从以下内容中省略它SQL

PreparedStatement pst = 
    conn.prepareStatement("insert into prodavac (ime, prezime) values (?, ?)");
pst.setString(1, ime);
pst.setString(2, prezime);
pst.executeUpdate();