简体   繁体   English

插入时出现Java常规错误... ???

[英]Java General Error On Insert…???

I am trying to do an Insert, Update and Delete on a table in MS Access. 我正在尝试在MS Access中的表上执行Insert, Update and Delete操作。 Everything works fine 一切正常

for a SELECT statement. 用于SELECT语句。 But when doing the other three operations, I don't seem to get any 但是当执行其他三个操作时,我似乎什么也没得到

errors, but the actions are not reflected on to the DB. 错误,但操作未反映到数据库上。 Please help... 请帮忙...

THe INSERT statement is as follows: INSERT语句如下:

PreparedStatement ps = con.prepareStatement("INSERT INTO Student VALUES (?, ?, ?, ?, ?, ?, ?, ?)");    
  ps.setInt(1,1);    
  ps.setString(2,"ish");    
  ps.setInt(3,100);    
  ps.setInt(4,100);    
  ps.setInt(5,100);    
  ps.setInt(6,300);
  ps.setInt(7,100);
  ps.setString(8,"A");     
  ps.executeUpdate();

Also may I know why PreparedStatement is used except for SELECT statement... 我也可能知道为什么除了SELECT语句外还使用PreparedStatement ...

I get this error: 我收到此错误:

Exception in thread "main" java.sql.SQLException: General error
        at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6986)
        at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
        at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3149)
        at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(JdbcOdbcPreparedState
ment.java:216)
        at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(JdbcOdbcPrepare
dStatement.java:138)
        at Student.main(Student.java:19)

This is my code... 这是我的代码...

    import java.sql.*;
    import java.io.*;

    class Student {
        public static void main(String args[]) throws SQLException, IOException,    ClassNotFoundException {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:odbc:Student","","");
            Statement st = con.createStatement();
            PreparedStatement ps = con.prepareStatement("INSERT INTO Student VALUES (?, ?, ?, ?, 
            ?, ?, ?, ?)");
            ps.setInt(1,1);
            ps.setString(2,"Girish");
            ps.setInt(3,100);
            ps.setInt(4,100);
            ps.setInt(5,100);
            ps.setInt(6,300);
            ps.setInt(7,100);
            ps.setString(8,"A"); 
            ps.executeUpdate();
            con.commit();
            con.close();
        }
    }

This can happen when you don't commit / close the connection. 当您不提交 / 关闭连接时,可能会发生这种情况。 Ensure that you're committing the connection after executing the statement and are closing the connection (and statement and resultset) in the finally block of the try block where they are been acquired and executed. 确保在执行语句后提交连接,并在try块的finally块中关闭连接(以及语句和结果集),在该块中已获取并执行了连接。

As to why the PreparedStatement is used, it's the common approach to avoid SQL injection attacks and to ease setting fullworthy Java objects like Date , InputStream , etc in a SQL query without the need to convert them to String . 至于为什么要使用PreparedStatement ,这是避免SQL注入 攻击并简化在SQL查询中设置有价值的Java对象(如DateInputStream等)的通用方法,而无需将它们转换为String

I believe your prepared statement is of the wrong format. 我认为您准备的陈述格式错误。 The documentation for INSERT INTO (available here: http://msdn.microsoft.com/en-us/library/bb208861(v=office.12).aspx ) gives this format: INSERT INTO的文档(在此处提供: http : //msdn.microsoft.com/zh-cn/library/bb208861 (v= office.12 ) .aspx )提供了以下格式:

Single-record append query: 单记录追加查询:

INSERT INTO target [(field1[, field2[, …]])]     VALUES (value1[, value2[, …])

You give the format: 您输入以下格式:

INSERT INTO target VALUES (value1[, value2[, …])

edit: To be more clear I believe you want something like: 编辑:更清楚地说,我相信你想要的东西是:

PreparedStatement ps = con.prepareStatement("INSERT INTO Student (Year, Name, field3 ...) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

Where Year, Name, field3 ... are the names of the fields you are trying to insert into. Year,Name,field3 ...是您要插入的字段的名称。

The main reason for using a PreparedStatement is security. 使用PreparedStatement的主要原因是安全性。 Generating a SQL query by concating strings is unsafe as the variable parts may contain SQL statements entered by a user. 通过包含字符串来生成SQL查询是不安全的,因为可变部分可能包含用户输入的SQL语句。 This would allow to execute statements like DROP TABLE * to the user (see SQL Injection ). 这将允许向用户执行诸如DROP TABLE *之类的语句(请参见SQL Injection )。 Theres is is a good idea only to use PreparedStatemnts if the SQL query is not static (doe snot contain variable parts). 仅当SQL查询不是静态的(不包含可变部分)时才使用PreparedStatemnts是一个好主意。 Therefore it would be better also to use PreparedStatement for SELECT statements. 因此,最好将PreparedStatement用于SELECT语句。

Edit : 编辑:

You try to Insert your Student Primary Key, if it's an Identity column, it will not work. 您尝试插入学生主键,如果它是“身份”列,则将不起作用。

You need to prepare your statement like this : 您需要像这样准备声明:

PreparedStatement ps = con.prepareStatement("INSERT INTO Student(Field1,Field2,Field3,Field4,Field5,Field6,Field7) VALUES (?, ?, ?, ?, ?, ?, ?)");

Without your Primary Key set, the DB will do it for you. 如果没有设置主键,数据库将为您完成。

.

.

.

Original post : 原始帖子:

There is a kind of similar question on StackOverflow . StackOverflow上也有类似的问题

You won't see any result from INSERT queries with Access until you close your Connection properly. 在正确关闭Connection之前,您将不会看到使用Access进行INSERT查询的任何结果。

Your code doesn't close any resources, which will surely bring you grief. 您的代码不会关闭任何资源,这肯定会给您带来悲伤。 Call the close methods (in reverse order if there are more than one) in a finally block. 在finally块中调用close方法(如果有多个,则以相反的顺序)。

Here is a class DataBaseUtils to help you if needed. 如果需要,这是一个DataBaseUtils类可为您提供帮助。

public class DatabaseUtils
{
    public static Connection createConnection(String driver, String url, String username, String password) 
        throws ClassNotFoundException, SQLException
    {
        Class.forName(driver);

        return DriverManager.getConnection(url, username, password);
    }

    public static void close(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace(e);
        }
    }

    public static void close(Statement statement)
    {
        try
        {
            if (statement != null)
            {
                statement.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace(e);
        }
    }

    public static void close(ResultSet rs)
    {
        try
        {
            if (rs != null)
            {
                rs.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace(e);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM