简体   繁体   English

使用Java插入mySql

[英]Using Java to insert into mySql

I am trying to insert some stuff into a sql database but my code isn't working. 我正在尝试将一些东西插入sql数据库,但是我的代码无法正常工作。 I'm kinda new to this, but after trying a few different things I am still stuck. 我对此有些陌生,但是尝试了一些不同的尝试后,我仍然感到困惑。 Any ideas as to how I could get my code to work? 关于如何使代码正常工作的任何想法? I'm not actually getting any errors, but the information is never entered into the database. 我实际上并没有收到任何错误,但是信息从未输入到数据库中。 Thanks in advance. 提前致谢。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class sqlIns
{
    public static void main (String []args)
    {
        String host = "jdbc:mysql://localhost:3306/tempdatat";
        String user = "root";
        String pass = "Nathan1";

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(host,user, pass);
            PreparedStatement statement = con.prepareStatement("Insert Into tempdata(id, timedata, tempdata) VALUES (?, ?, ?)");
            statement.setInt(1, 1);
            statement.setInt(2, 30);
            statement.setDouble(3, 78.30);
            statement.execute();
            statement.close();
            con.close();
        }
        catch(Exception e)
        {
             System.out.println(e.getMessage());
        }
        finally
        {
                 System.out.println("Done!");
        }

     }
}

Your DB table names are different in your host variable & sql query . 您的主机变量和sql查询中的数据库表名称不同。 Make sure of correct table name of database at both places. 确保两个地方的数据库表名称正确。 And, Use all lowercase letters for sql query. 并且,将所有小写字母用于sql查询。

Try it: 试试吧:

insert into tempdata(id, timedata, tempdata) values (?, ?, ?)

Instead of : 代替 :

Insert Into tempdata(id, timedata, tempdata) VALUES (?, ?, ?)

Your code is actually pretty good, and you almost got it right. 您的代码实际上非常好,并且您几乎正确了。

Your only mistake is that for INSERT you need to use: 您唯一的错误是对于INSERT您需要使用:

statement.executeUpdate();

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

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