gpt4 book ai didi

java - JDBC MySQL 查询错误?

转载 作者:行者123 更新时间:2023-11-29 03:54:42 25 4
gpt4 key购买 nike

我试图将一些数据插入到 mysql 数据库中,但出现错误,而且我无法通过代码找到错误。我不擅长mysql。

String insertQuery = "insert into books(title, author, description, prize)values("
+ title
+ ","
+ author
+ ","
+ desc
+ ", "
+ prize
+ ");";

mysql> describe books;
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| book_id | int(11) | NO | PRI | NULL | |
| title | varchar(64) | YES | | NULL | |
| author | varchar(64) | YES | | NULL | |
| description | varchar(500) | YES | | NULL | |
| prize | float | YES | | NULL | |
| added | datetime | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
6 rows in set (0.01 sec)

我得到的错误是,

Query: insert into books(title, author, description, prize)values(sfdfdf,fdfdf,Please    limiasasaat your response to 500 characters., 78.9);
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'limiasasaat your response to 500 characters., 78.9)' at line 1

最佳答案

您的字符串值没有用单引号引起来。试试这个:

String insertQuery = "insert into books(title, author, description, prize)values('"
+ title
+ "','"
+ author
+ "','"
+ desc
+ "', "
+ prize
+ ");";

Example of Prepared Statement at RoseIndia

更新 1

PreparedStatement 示例:

//other codes here
String iSQL = "Insert into books(title, author, description, prize) values (?,?,?,?)";
// con is your active connection object
PreparedStatement pstmt = con.prepareStatement(iSQL);
pstmt.setString(1, title);
pstmt.setString(2, author);
pstmt.setString(3, desc);
pstmt.setFloat(4, prize);
pstmt.executeUpdate();
//other codes here

但不要忘记在您的类(class)顶部添加以下声明:import java.sql.*;

关于java - JDBC MySQL 查询错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10672478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com