I am new to Java and MYSql in fact using this combination first time and facing real trouble. I want to insert few records in a table but unable to do so. Following are the fields and datatype in the table named tbl_cdr in MySql.
**Field** **Type**
DATEANDTIME datetime NULL
VALUE1 int(50) NULL
VALUE2 varchar(50) NULL
VALUE3 varchar(50) NULL
VALUE4 varchar(50) NULL
VALUE5 varchar(50) NULL
The record I want to insert contains following values
2014-05-19 02:37:18, 405, MGW190514023718eab4, 923016313475, IN, ALERTSC
I am using following query and statements to Insert record in table
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", " + columnsList.get(2) + ", " + columnsList.get(3) + ", " + columnsList.get(4) + ", " + columnsList.get(5) + ")";
try
{
Statement qryStatement = conn.createStatement();
qryStatement.executeUpdate(sqlQuery);
qryStatement.close();
} catch (SQLException ex)
{
Logger.getLogger(CdrProject.class.getName()).log(Level.SEVERE, null, ex);
}
But when I reach the statement qryStatement.executeUpdate(sqlQuery); exception is thrown as:
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 '02:37:18, 405, MGW190514023718eab4,
923016313475, IN, ALERTSC)' at line 1
value2 ,value3 ,value4 and value 5 are varchars so it should be written within ''.
Do like this
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", '" + columnsList.get(2) + "',' " + columnsList.get(3) + "',' " + columnsList.get(4) + "',' " + columnsList.get(5) + "')";
You're inserting the date incorrectly. MySQL allows you to insert a string literal or a number.
You're trying to use 02:37:18 as a number, when really you should be using it as a string literal: '02:37:18'
Here is the MySql Reference describing this.
You're also not treating your varchars as strings either, they should be enclosed with quotes.
Related
I am hoping someone can find what is the issue with my query because I am unable to see fault in it and Oracle SQL Developer seems to run the same query as the code in my Java Swing Application just fine.
My query in SQL Developer:
SELECT
ad.ID,ad.Script_Name,ad.Current_Status,
ad.Issues_found_during_run,ad.Testers,
ad.Run_Date,ad.Tools,u.fTag,u.role,
dbms_lob.substr(u.avatar)
FROM
allData ad
INNER JOIN
users u
ON
u.fTag = ad.lastUserWhoUpdated
GROUP BY
ad.ID,ad.Script_Name,ad.Current_Status,
ad.Issues_found_during_run,ad.Testers,
ad.Run_Date,ad.Tools,u.fTag,u.role,
dbms_lob.substr(u.avatar)
ORDER BY
ad.ID ASC;
Which run perfectly and returns the needed records I would be expecting it to.
However, that same query in my Java Swing App does not seem to like it as it gives me the error of:
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended.
My Java Swing App code:
connectToDB();
String query =
"SELECT " +
"ad.ID," +
"ad.Script_Name," +
"ad.Current_Status," +
"ad.Issues_found_during_run," +
"ad.Testers," +
"ad.Run_Date," +
"ad.Tools," +
"u.fTag," +
"u.role," +
"dbms_lob.substr(u.avatar) " +
"FROM " +
"allData ad " +
"INNER JOIN " +
"users u " +
"ON " +
"u.fTag = ad.lastUserWhoUpdated " +
"GROUP BY " +
"ad.ID," +
"ad.Script_Name," +
"ad.Current_Status," +
"ad.Issues_found_during_run," +
"ad.Testers," +
"ad.Run_Date," +
"ad.Tools," +
"u.fTag," +
"u.role," +
"dbms_lob.substr(u.avatar) " +
"ORDER BY " +
"ad.ID;";
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
etc..etc..
My structure for those 2 tables is:
SCRIPT_NAME VARCHAR2(100 BYTE)
CURRENT_STATUS VARCHAR2(50 BYTE)
ISSUES_FOUND_DURING_RUN VARCHAR2(150 BYTE)
TESTERS VARCHAR2(30 BYTE)
RUN_DATE DATE
TOOLS VARCHAR2(20 BYTE)
T_SUITE NUMBER(38,0)
NOE2 VARCHAR2(5 BYTE)
NOE3 VARCHAR2(5 BYTE)
ID NUMBER(38,0)
LASTUSERWHOUPDATED NUMBER
DATELASTMOD DATE
FTAG NUMBER(38,0)
ROLE VARCHAR2(15 BYTE)
AVATAR CLOB
So, what could I be missing?
Remove semicolon after the ad.ID like below. You don't need it
"ORDER BY " +
"ad.ID";
I have 2 tables. A booking table and a room table. In the booking table I have the following columns: BookingID StartDate EndDate CustomerID RoomID
In the Room table I have the following columns: RoomID RoomSize
I am creating a booking system. I want to be able to query the database where I am able to get a list of rooms that are booked between 2 dates which are also based on size (small, medium or large) types.
E.g. if user clicks on small room and enters dates between 2010-02-02 to 2010-02-25 then 4 should appear as my database contains 4 small rooms that are booked between those dates.
This is what I have so far:
String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize is " + type + ") AND ((Booking.StartDate between "+ startD +" AND " + endD + ") OR (Booking.EndDate between "+ startD + " AND " + endD + "))";
This is the error I am getting:
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 'Medium) AND ((Booking.StartDate between 2016-02-09 AND 2016-02-09) OR (Booking.E' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
I am new to SQL and having trouble doing this. Also, is my logic right?
startD and endD represents the dates that the user has entered and typeOfRoom represent the type of the room the user wants to book; e.g. eithier Small, Medium or Large
Do not use string concatenation to insert user-supplied values into SQL, especially for strings. It will leave you open to SQL Injection attacks, and SQL syntax issues. Use a PreparedStatement.
Also, replace is with =.
String sql = "select RoomID" +
" from Booking" +
" where RoomID in (" +
"select Room.RoomID" +
" from Room" +
" where Room.RoomSize = ?" +
")" +
" and ((Booking.StartDate between ? AND ?)" +
" or (Booking.EndDate between ? AND ?))";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, type);
stmt.setDate (2, startD);
stmt.setDate (3, endD);
stmt.setDate (4, startD);
stmt.setDate (5, endD);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
// code here
}
}
}
The date handling look ok I think, but you need to quote the type string in the statement. And you should not use is, just use normal =
String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize = '" + type + "') AND ((Booking.StartDate between "+ startD +" AND " + endD + ") OR (Booking.EndDate between "+ startD + " AND " + endD + "))";
Can you try if this statement works? I have replaced the 'is' keyword with '=' operator and put all the variables between "".
String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize = \"" + type + "\") AND ((Booking.StartDate between \""+ startD +"\" AND \"" + endD + "\") OR (Booking.EndDate between \""+ startD + "\" AND \"" + endD + "\"))";
I'm trying to update the column amount if the buyid (primary key) is a specific value.
UPDATE portfolio set amount=40 WHERE buyid=3
I work with JDBC and MySql, everytime I try to execute the statement i get the following exception:
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 'buyid=3' at
line 1
table structure of portfolio:
buyid int
username varchar
stockname varchar
priceperstock float
amount int
Javasourcecode:
public void sellStock(int buyid, int amount, float currentprice, String user) {
...
try {
stmt = this.conn.createStatement();
System.out.println(fetchedamount);
System.out.println("UPDATE portfolio
SET amount=" + fetchedamount
+ " WHERE buyid=" + buyid);
stmt.execute("UPDATE stockman.portfolio
SET amount=" + fetchedamount
+ "WHERE buyid=" + buyid+"");
// update capital
newmoney = amount * currentprice + oldmoney;
} catch (SQLException ee) {
ee.printStackTrace();
}
At stmt.execute() Your generated query is like
"UPDATE stockman.portfolio set amount=23WHERE buyid=54 "
Here 23Where is one whole string so you have to give space between these two.
Give space between " and Where like the following:
" WHERE buyid="
And remove the last +""
Just add space before Where it will solve the problem.
stmt.execute("UPDATE stockman.portfolio
SET amount=" + fetchedamount
+ " WHERE buyid=" + buyid+"");
Repleace the stm.execute line with:
stmt.execute("UPDATE stockman.portfolio SET amount=" + fetchedamount + " WHERE buyid=" + buyid+" ");
Or:
stmt.execute("UPDATE stockman.portfolio SET amount='" + fetchedamount + "' WHERE buyid='" + buyid+"' ");
I am trying to make a variable Table name through Java.
My code is :
public void createTable(String tableName){
try {
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE '"+tableName+"'" +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
}
catch (SQLException e){
e.printStackTrace();
}
}
It gives me a syntax error saying:
Incorrect syntax near 'VariableTableNameIChose'.
Does anyone have any ideas?
It could be one of 2 things or the combination of both.
Maybe the single quotes around the table name are not valid in your database. So do like this:
stmt.executeUpdate("CREATE TABLE "+tableName+" " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
Or maybe you need a spaces between the table name and the ( following after:
Statement stmt = con.createStatement();
// v this one was missing
stmt.executeUpdate("CREATE TABLE '"+tableName+"' " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
The table name is an identifier. Identifiers do not use single quotes (in standard SQL).
"CREATE TABLE '"+tableName+"' "
Will result in
CREATE TABLE 'foobar'
which is invalid SQL. You need to remove the single quotes:
"CREATE TABLE "+tableName+" " + ...
As the table name is apparently a user input, you might actually want to use quoted identifiers (although this is in general a bad idea). Identifiers are quoted using double quotes in the SQL standard:
"CREATE TABLE \""+tableName+"\" " + ...
Using Derby as my data base driver and tying to execute SQL query through java,
there was a error that was encounter, when tried to execute this particular query
stmt.executeQuery("insert into " + "TEST " + "values (" + dataTimeRev + ", "
+ dataType + "," + obj + ")" );
Here dataTimeRev, dataType and obj are variables with data.
The error that was stated was like this
java.sql.SQLSyntaxErrorException: VALUES clause must contain at least one element. Empty elements are not allowed.
if the column data type is VARCHAR you will have to pass the value in qoutes like 'value' for that you should do as below
String query = "insert into TEST values('"+dataTimeRev+"', '"+dataType+"','"+obj+"')";
stmt.executeQuery(query);
Verify that dataTimeRev, dataType and obj are not null and not blank.
I am not sure if Derby follows SQL syntax. But if the values are of type varchar, then it should be enclosed in single quotes ('). For example:
stmt.executeQuery("insert into " + "TEST " + "values ('" + dataTimeRev + " ', ' "
+ dataType + " ',' " + obj + " ')" );
Try this:
stmt.executeQuery("insert into TEST values ('" + dataTimeRev + "', "'+ dataType + "',"' + obj + "')" );
One of the causes of this error is trying to insert a Type that isn't a String (Date, Double, Integer e.t.c, surrounded by the single quotation mark ''
For example my table was declared like this:
String createTableStatement = "CREATE TABLE PRODUCT"+ "(product_id INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
"product_name CHAR(80), "+
"price DOUBLE," +
"supplier CHAR(50))";
So I was doing:
statement.executeUpdate("INSERT INTO PRODUCT (PRODUCT_NAME, PRICE, DATE_SUPPLIED, QUANTITY, SUPPLIER) VALUES " +
"('" + productName + "', " + "'" + price + "', " + "'" + supplier +"')");
instead of:
statement.executeUpdate("INSERT INTO PRODUCT (PRODUCT_NAME, PRICE, DATE_SUPPLIED, QUANTITY, SUPPLIER) VALUES " +
"('" + productName + "', " + price + ", " + "'" + supplier +"')");