使用 jdbc 将数据插入数据库

Posted

技术标签:

【中文标题】使用 jdbc 将数据插入数据库【英文标题】:inserting data into database using jdbc 【发布时间】:2014-01-13 07:43:06 【问题描述】:

我有一个 java 桌面应用程序。 我正在尝试将两个文本字段中的数据插入到数据库中。 但是遇到一些运行时错误。 帮我解决它。

这是我的代码 sn-p

final String s1 = t1.getText();
final String s2 = t2.getText();
jb.addActionListener(new ActionListener() 

    public void actionPerformed(ActionEvent e) 
        String host = "jdbc:derby://localhost:1527/Details";
        String uName = "rajil";
        String uPass = "rajil";
        try 
            Connection con = DriverManager.getConnection(host, uName,uPass);
            Statement st = con.createStatement();
            String q1 = "insert into name (name,id) values('" + s1 + "','" + s2 + "')";
            st.executeQuery(q1);
         catch (SQLException ex) 
            Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
        
    
);

【问题讨论】:

你遇到了什么错误? 哪里出错了? java.sql.SQLException:executeQuery 方法不能用于更新。在 org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source) at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source) at org.apache.derby.client.am.Statement.executeQuery (来源不明) 没有语法错误。它的运行时 不要将堆栈跟踪放在 cmets 中。相反,edit the question.. 【参考方案1】:

st.executeQuery(q1); 更改为st.executeUpdate(q1);

首先加载驱动程序

Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();

【讨论】:

好的。但是在收到另一个错误 java.sql.SQLSyntaxErrorException: Table/View 'DTS' 不存在之后。在 org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source) 在 org.apache.derby.client.am.SqlException.getSQLException(Unknown Source) 在 org.apache.derby.client.am.Statement.executeUpdate (来源不明) @user3007882 为什么要切换已接受的答案? @user3007882 这是你的选择。【参考方案2】:

您还必须使用以下语句来加载驱动程序类

Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();

例如mysql

Class.forName("com.mysql.jdbc.Driver");

详情请看以下链接

http://www.vogella.com/articles/ApacheDerby/article.html

【讨论】:

以上是关于使用 jdbc 将数据插入数据库的主要内容,如果未能解决你的问题,请参考以下文章

使用 R JDBC 将数据插入到 Impala

使用 JDBC 将记录插入数据库时​​无法修复错误

JMeter:使用 JDBC 请求将记录插入数据库

使用 JDBC 将引用另一个表的数据插入 MySQL

使用 JDBC 从 MATLAB 将数据插入 PostgreSQL 表会引发 BatchUpdateException

如何使用 GWT、HTML 和 JDBC 或 Hibernate 将数据插入 MySQL 数据库?