美文网首页
java实现mysql插入数据

java实现mysql插入数据

作者: oooon | 来源:发表于2017-12-01 11:45 被阅读0次
这个操作是在eclipse下进行的

在连接的过程中遇到了一些问题:
1、You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table-test(num)values(8)' at line 1
大概意思就是说sql语句有语法错误,让检查一下MySQL版本对应的手册
我的解决办法是:我在MySQL Workbench中可视化操作了一下向数据表中插入数据,对比了一下eclipse里边的语句和workbench里边的插入语句区别,书上代码在eclipse中是这样的String sql = "insert into table-test(num)values(7)";其中"table-test"是我自己在数据库中建的一个表,运行的时候就出现了上边的错误,但在workbench中sql语句是这样的INSERT INTO `table1`.`table-test` (`num`) VALUES ('9');它的语句中用了“ table1.table-test ”它用了两个反向单引号把“table1”、“table-test”包起来了;我试着也像这样改了一下,结果就成功了,在java代码中也可以不用“table1.”,这样也能成功
2、Duplicate entry '8' for key 'PRIMARY'大概意思是重复输入了8,数据表里有的就不能再插入了,改成数据表里没有的就可以执行成功了
代码:

import java.sql.*;
public class JDBC{
    private static final String URL = "jdbc:mysql://localhost:3306/table1?useSSL=true";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/table1?user=root&password=123456&useSSL=true");
            Statement statement = conn.createStatement();//获取对象
            String sql = "insert into `table-test`(num)values(7)";//看了看mysql的插入语句,用两个反单引号"``"
                                     //把表名称包起来,这样就能实现数据的插入更新了
            statement.executeUpdate(sql);
            statement.close();
            conn.close();
        
        }catch(SQLException e) {
            e.printStackTrace();
        }catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
         
    }
}

相关文章

网友评论

      本文标题:java实现mysql插入数据

      本文链接:https://www.haomeiwen.com/subject/wsiibxtx.html