为什么我的数据无法插入数据库?

时间:2021-01-23 06:04:14

标签: java database

我无法将输入保存到我的数据库中。有谁能够帮我? 存在 SSL 问题,但可以通过将 SSL 设置为 false 来解决,但数据似乎只能读取但无法保存到我的数据库中。

package first;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Connection;
import javax.swing.JOptionPane;

public class CustomersForm extends javax.swing.JFrame {
    public CustomersForm() {
        initComponents();
    }

    private void jButton_addcusActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String connectionURL = "jdbc:mysql://localhost:3308/java_his_db";
            Connection con = DriverManager.getConnection(connectionURL, "root", "");
            String sql = "Insert into customers ('fname') values (?)";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(2, jTextField_fname.getText());
            ps.executeUpdate();
            System.out.println("YES");
            con.close();
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(rootPane, "Blank or Wrong User Profile", "Insert Error", 2);
        }  
    }                                                         

    private void jTextField_fnameActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        // TODO add your handling code here:
    }

2 个答案:

答案 0 :(得分:1)

您的查询中只有一个占位符,因此在此语句中索引应为一:ps.setString(1, jTextField_fname.getText());

答案 1 :(得分:1)

Answer by Andrew Vershinin 看起来是正确的。您的占位符编号 2 应为 1

您评论说您仍然有错误,但忽略了描述这些错误。错误可能来自 INSERT 语句的 SQL。您不应该制作列名称的字符串。你把单引号放在不属于它们的地方。作为 commented by Abra'fname' 周围的单引号使该文本变成 string literal 而不是列的名称。在需要列名的 SQL 中,字符串文字没有意义。

您的代码:

String sql = "Insert into customers ('fname') values (?)";

……应该是:

String sql = "INSERT INTO customers ( fname ) values (?) ;";

在我下面的示例中,您将看到类似的代码:

INSERT INTO person_ ( name_ )
VALUES ( ? )
;

这是一个完整的示例应用程序,它创建一个包含一个表 person_ 的数据库,在该表中插入两行,然后检索这两行。您可以看到调用 PreparedStatement#set… 方法的工作原理。

此代码使用 H2 Database Engine。但是以下代码对于任何 SQL 数据库都几乎相同。

提示:将数据库访问代码与 GUI 代码分开。在尝试与 GUI 集成之前,先确定数据库代码并使其顺利运行。

提示:使用 try-with-resources 自动关闭您的连接、语句、结果集等。

提示:始终包含可选的分号语句终止符。在某些地方没有它你可以逃脱,但在其他地方可能会弄乱代码。保持整洁,保持一致。

package work.basil.example;

import com.thedeanda.lorem.LoremIpsum;
import org.h2.jdbcx.JdbcDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.Objects;

public class DbH2Example
{
    public static void main ( String[] args )
    {
        DbH2Example app = new DbH2Example();
        app.demo();
    }

    private void demo ( )
    {
        // -------------------|  DataSource  |---------------------------------
        DataSource dataSource = null;
        {
            org.h2.jdbcx.JdbcDataSource ds = Objects.requireNonNull( new JdbcDataSource() );  // Implementation of `DataSource` bundled with H2.
            ds.setURL( "jdbc:h2:mem:MyExampleDb;DB_CLOSE_DELAY=-1" );  // To keep an in-memory database after disconnecting, add DB_CLOSE_DELAY=-1 argument.
            ds.setUser( "scott" );
            ds.setPassword( "tiger" );
            ds.setDescription( "An example database showing how to insert a row." );
            dataSource = ds;
        }
        Objects.requireNonNull( dataSource );

        // -------------------|  Prepare database  |---------------------------------
        {
            String sql =
                    """
                    DROP TABLE IF EXISTS person_ 
                    ;
                    CREATE TABLE IF NOT EXISTS person_
                    (
                        name_ text NOT NULL  ,
                        row_created_ TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP() ,
                        id_ IDENTITY NOT NULL ,
                        CONSTRAINT person_pkey_ PRIMARY KEY ( id_ )
                    )
                    ;
                    """;
            try (
                    Connection conn = dataSource.getConnection() ;
                    Statement stmt = conn.createStatement() ;
            )
            {
                System.out.println( "INFO - Preparing database. Message # adaaf8ed-8922-4c15-addf-35f6ead1442b. " + Instant.now() );
                stmt.executeUpdate( sql );
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }

        // -------------------|  Insert row  |---------------------------------
        {
            System.out.println( "INFO - Insert rows. Message # 7a7e1c0a-7e97-4ebc-8d24-6e9ea20f8b5f. " + Instant.now() );
            String sql =
                    """
                    INSERT INTO person_ ( name_ )
                    VALUES ( ? )
                    ;
                    """;
            try
                    (
                            Connection conn = dataSource.getConnection() ;
                            PreparedStatement ps = conn.prepareStatement( sql ) ;
                    )
            {
                ps.setString( 1 , "Alice" );
                ps.executeUpdate();

                ps.setString( 1 , "Bob" );
                ps.executeUpdate();
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }

        // -------------------|  Dump rows  |---------------------------------
        {
            System.out.println( "INFO - Dump rows. Message # f6b786be-ef1e-4b97-9779-59bc84566e3d. " + Instant.now() );
            try
                    (
                            Connection conn = dataSource.getConnection() ;
                            Statement stmt = conn.createStatement() ;
                    )
            {
                String sql =
                        """
                        TABLE person_
                        ;
                        """;
                try (
                        ResultSet rs = stmt.executeQuery( sql ) ;
                )
                {
                    while ( rs.next() )
                    {
                        String name = rs.getString( "name_" );
                        Instant whenCreated = rs.getObject( "row_created_" , OffsetDateTime.class ).toInstant();
                        long id = rs.getLong( "id_" );
                        System.out.println( "whenCreated = " + whenCreated + " | " + "id : " + id + " | " + "name = " + name );
                    }
                }
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }
    }
}

运行时。

INFO - Preparing database. Message # adaaf8ed-8922-4c15-addf-35f6ead1442b. 2021-01-23T06:44:22.363589Z
INFO - Insert rows. Message # 7a7e1c0a-7e97-4ebc-8d24-6e9ea20f8b5f. 2021-01-23T06:44:22.389564Z
INFO - Dump rows. Message # f6b786be-ef1e-4b97-9779-59bc84566e3d. 2021-01-23T06:44:22.414178Z
whenCreated = 2021-01-23T06:44:22.393600Z | id : 1 | name = Alice
whenCreated = 2021-01-23T06:44:22.413983Z | id : 2 | name = Bob