public class DataBase {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/company", , )) {
Type[] types = { new GraphicCard(), new HardDrive(), new Keyboard(), new Memory(), new Monitor(), new Mouse(), new Processor() };
Product product = new Product(10, types);
Range rangeUnitPrice = new Range(10_000, 220_000);
Range rangeQuantity = new Range(0, 20);
Statement statement = connection.createStatement();
while (product.getNumberOfEntery() > 0) {
String typeAndCatagory = product.getRandomType();
String name = product.getName(typeAndCatagory);
String description = product.getDescription();
double unit_Price = product.randomUnit_PriceGenerator(name, 'x', rangeUnitPrice);
int quantity_In_Stock = product.generateQuantity_In_Stock(rangeQuantity);
String brand = product.getRandomBrand();
System.out.println("Name: " + name + ", " + "Type: " + typeAndCatagory + ", " + "Random price: " + unit_Price + ", " + "Quantity in stock: " + quantity_In_Stock + ", " + "Random brand: " + brand);
String query = "INSERT INTO product VALUES (" + name + ", " + description + ", " + unit_Price + ", " + quantity_In_Stock + ", " + brand + ", " + typeAndCatagory + ", " + typeAndCatagory + ")";
statement.executeUpdate(query);
product.decreasesNumberOfEntrees();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The query doesn't work, and the first value is the default (PRIMARY KEY AUTO-INCREMENT), which I don't need to specify. The error is below
java.sql.SQLSyntaxErrorException: 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 '10 AMD graphic card Gamer Edition, ,
180657.63138583858, 6, HP, Graphic Card, Gr' at line 1
You format a string in this line to use as an SQL statement:
String query = "INSERT INTO product VALUES (" + name + ", " + description + ", " + unit_Price + ", " + quantity_In_Stock + ", " + brand + ", " + typeAndCatagory + ", " + typeAndCatagory + ")";
Something is wrong with this statement that makes it produce a syntax error. What is wrong?
It's difficult to debug this by staring at the Java expression. It's confusing to look at all the " and + and see what's wrong.
It would be easier to see what's wrong if you can see the final result of the string, not the Java expression that builds a string.
So before you execute it, try printing it out:
System.out.println(query);
Then the problem may be more clearly visible.
I predict it will look something like this:
INSERT INTO product VALUES (10 AMD graphic card Gamer Edition, , 180657.63138583858, 6, HP, Graphic Card, Gr...
This is missing quotes around the string values in your VALUES clause. It's not valid SQL.
The best solution is to learn to use query parameters. Then you don't have to worry about quotes around values. And the code is more secure from SQL injection.
In your case, something like the following:
String query = "INSERT INTO product VALUES (?, ?, ?, ?, ?, ?, ?)";
Statement statement = connection.prepareStatement(query);
while (product.getNumberOfEntery() > 0) {
// set the values for all your variables...
statement.setString(1, name);
statement.setString(2, description);
statement.setDouble(3, unit_Price);
statement.setInt(4, quantity_In_Stock);
statement.setString(5, brand);
statement.setString(6, typeAndCatagory);
statement.setString(7, typeAndCatagory);
statement.executeUpdate();
}
There are two problems with your code:
The major one is, your code is vulnerable to SQL Injection.
You will have to enclose the text values withing single quotes yourself.
The solution to both the problem is using PreparedStatement as shown below:
String query = "INSERT INTO product VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = con.prepareStatement(query)) {
//...
pstmt.setString(1, name);
pstmt.setString(2, description);
pstmt.setDouble(3, unit_Price);
//...
pstmt.executeUpdate();
}
Also, I suggest you always follow Java naming conventions e.g. unit_Price should be named as unitPrice.
Related
if (Baglan() == false) { return false; }
try{
String generatedColumns[] = {"ID","TAHSILATNO"};
String sSql = "Declare nId number := 0;" +
" nKey number := 0;" +
" BEGIN" +
" Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
" INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, 53);" +
" EXCEPTION " +
" WHEN DUP_VAL_ON_INDEX THEN" +
" Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
" Select Nvl(Max(tahsilatno),0) + 1 INTO nKey From bvktahsilatno WHERE Yili = 2018;" +
" INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, nKey);" +
"END;";
//VtStatement = VtConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//VtStatement.execute(pSql);
//PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS );
//PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, generatedColumns );
PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS);
System.out.println("oracle cumle : " + sSql);
int nAdet = VtStatement.executeUpdate();
System.out.println("Hatayok/Adet : " + nAdet);
ResultSet rs = VtStatement.getGeneratedKeys();
int id=0;
while (rs.next()) {
id = rs.getInt(1);
}
System.out.println("Oracle Inserted ID -" + id); // display inserted record
return true;
} catch (SQLException e) {
return false;
}
I want to ask a question about retrieving created keys on Oracle Db after insert query. My code is as above but generated keys values are not showed on the terminal. How can i get generated column values without creating sequence ? Many form pages say that it is possible as using sequence for id or other column. Also id is primary key, tahsilatno is unique index. I can overcome this problem?
Thank you for your helping from now
public void Update(String name, String mobile, String email, String car, String model, String year, String color, String plate_no, String plateletters,String gear, String km, String date,String licesnse,String status, String notes){
Connection conn = null;
try{
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("connected");
Statement stmt = (Statement) conn.createStatement();
String ins = "update car"
+ "set Name = '"+name+"' , "
+ "Email = '"+email+"' , "
+ "Car = '"+car+"' , "
+ "Model = '"+model+"' , "
+ "Year = '"+year+"' , "
+ "Color = '"+color+"' , "
+ "Plateno = '"+plate_no+"' , "
+ "Plateletters = '"+plateletters+"' , "
+ "Gearbox = '"+gear+"' , "
+ "Km = '"+km+"' , "
+ "Date = '"+date+"' , "
+ "License = '"+licesnse+"' , "
+ "Status = '"+status+"' , "
+ "Notes = '"+notes+"' "
+ "where Mobile = '"+mobile+"' ";
stmt.execute(ins);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
System.err.println(e);
return;
}
}
**i have tried prepared statment and stmt.executeUpdate(ins); but nothing workes !!
Please help!**
the error :
java.sql.SQLSyntaxErrorException: 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 '= 'ahmed' , Email = 'ahmed#hotmail.com' , Car = 'honda' , Model = 'hondaz' , Yea' at line 1
You need to make sure you add proper space between elements in your SQL query:
String ins = "update car"
should be
String ins = "update car "
A good approach to doing this is to write and execute your SQL in your database query tool (SQL developer, phpMyAdmin, whatever) and make sure your syntax is good before trying to re-write it in Java.
Use a preparedStatement instaed of a Statement.
Connection conn = null;
try{
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
PreparedStatement pstm = conn.prepareStatement(
"update car "
+ "set Name = ? ,"
+ "Email = ? ,"
+ "Car = ? ,"
+ "Model = ? ,"
+ "Year = ? ,"
+ "Color = ? ,"
+ "Plateno = ? ,"
+ "Plateletters = ? ,"
+ "Gearbox = ? ,"
+ "Km = ?,"
+ "Date = ?,"
+ "License = ?, "
+ "Status = ?, "
+ "Notes = ? "
+ "where mobile = ?"
);
pstm.setObject(1, name);
pstm.setObject(2, email);
pstm.setObject(3, car);
pstm.setObject(4, model);
pstm.setObject(5, year);
pstm.setObject(6, color);
pstm.setObject(7, plate_no);
pstm.setObject(8, plateletters);
pstm.setObject(9, gear);
pstm.setObject(10, km);
pstm.setObject(11, date);
pstm.setObject(12, licesnse);
pstm.setObject(13, status);
pstm.setObject(14, notes);
pstm.setObject(15, mobile);
pstm.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}
I am using hibernate application in java to retrieve and update database.
During updating a table,i forming an sql query as follows,
String qry = "UPDATE " + entity + " SET " + htmlColumn + " ='"+value+"' WHERE " + id + " = " + primaryId;
where value is a html string which contains single quotes sometimes.
How to escape ignore/escape the single quotes and update the table successfully
Thanks
use PreparedStatement for this
String qry = "UPDATE " + entity +
" SET " + htmlColumn + " = ? " +
"WHERE " + id + " = ?";
PreparedStatement pstmt = con.prepareStatement(qry);
pstmt.setString(1, value);
pstmt.setInt(2, primaryId);
pstmt.executeUpdate();
PreparedStatement
Don't set values directly.
currentSession()
.createQuery("UPDATE " + entity + " SET " + htmlColumn +
" = :value WHERE " + id + " :id")
.setParameter("value", value).setParameter(":id",id).executeUpdate();
You can replace the single quote with a double single quote. value.replace("'","''"); but you will need to cater for more than just that because your value can easily allow for SQL Injection if it is not properly catered for.
You can use preparedstatement as :
String query= "UPDATE " + entity + " SET " + htmlColumn + " =? WHERE " + id + " = " + primaryId;
PreparedStatement ptmt = con.prepareStatement(query);
ptmt.setString(1, value);
I am trying to insert records into SQL Server using jdbc conn (in java).
I am able to insert into SQL, if I manually copy the query statement in the java file. But its not inserting from the code?
Please help, where am I committing mistake?
PreparedStatement preparedStatement = null;
if (conn != null) {
System.out.println("Connection Successful!");
}
//Create a Statement object
Statement sql_stmt = conn.createStatement();
//Create a Statement object
Statement sql_stmt_1 = conn.createStatement();
//Result Set for Prouduct Table
ResultSet rs = sql_stmt.executeQuery("SELECT MAX(ID), MAX(RG_ID), MAX(WG_ID) FROM " + strDBName + ".[dbo].Product");
if ( rs.next() ) {
// Retrieve the auto generated key(s).
intID = rs.getInt(1);
intRG_ID = rs.getInt(2);
intWG_ID = rs.getInt(3);
}
for (int iCount = 0 ;iCount < arrListLevel_1_Unique.size(); iCount++)
{
//Result Set for Prouduct Table
sql_stmt_1.executeUpdate("\n IF NOT EXISTS(SELECT 1 FROM " + strDBName + ".[dbo].Product WHERE [Name] NOT LIKE '" + arrListLevel_1_Unique.get(iCount) + "') "
+ "\nINSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ "VALUES ( '" + arrListLevel_1_Unique.get(iCount) + "',"
+ + (intWG_ID + intRowIncrement) + ", " + (intWG_ID + intRowIncrement + 1) + ", 5828)");
intRowIncrement++ ;
}
rs.close();
sql_stmt.close();
sql_stmt_1.close();
//Close the database connection
conn.close();
You have two plus signs + in the fifth row:
+ + (intWG_ID + intRowIncrement) + ...
Otherwise, the problem may lie in the IF ... statement. You can try this instead:
sql_stmt_1.executeUpdate(
" INSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ " SELECT '" + arrListLevel_1_Unique.get(iCount) + "',"
+ (intWG_ID + intRowIncrement) + ", "
+ (intWG_ID + intRowIncrement + 1) + ", 5828 "
+ " WHERE NOT EXISTS( SELECT 1 FROM " + strDBName
+ ".[dbo].Product WHERE [Name] LIKE '"
+ arrListLevel_1_Unique.get(iCount) + "') "
) ;
I think the problem lies on the "\n", have you tried eliminating those 2 of "\n" and see if it's working?
Actually this kind of implementation (building SQL string with string concatenation) is really bad. At first is prone to SQL injection, and then secondly you will have problem if the value to be inserted contains character single quote or ampersand.
Instead, you should use "prepare statement".
And it's tidier to store the SQL string into a variable before executing it. So that you can log it (for debug purpose), roughly something like this:
String sqlCommand = "select * from " + tableName;
System.out.println(sqlCommand);
sqlStatement.executeUpdate(sqlCommand);
P.S. it is not advised to use system.out.println for debug, you should implement a proper logging system.
I'm new to connecting java with a mysql database. What's wrong with my query here:
PreparedStatement statement = conn.prepareStatement("SELECT * FROM q_table, choices, answers WHERE q_table.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'");
In your statement " ... q_table.QID='" + number_input + "' AND ... the variable number_input is enclosed in a single quote ('). This is used for string lieterals. If you remove the single quote it should work:
String prest= "SELECT * FROM q_table, choices, answers WHERE questions.QID=? AND choices.CID=? AND answers.AID=?";
prest.setInt(1,1980);
prest.setInt(2,2004);
.
.
ResultSet rs = prest.executeQuery();
while (rs.next()){
String mov_name = rs.getString(1);
int mov_year = rs.getInt(2);
count++;
System.out.println(mov_name + "\t" + "- " + mov_year);
}
System.out.println("Number of records: " + count);
prest.close();
con.close();
Well, the first problem is that you're opening yourself up to a SQL injection attack by including values directly in your SQL. Use a parameterized query instead.
Now we can't really tell what's wrong beyond that, although the fact that you're quoting a number seems suspicious, as does the fact that you're using the same value for a question ID, a choice ID and an answer ID. That seems unlikely to be appropriate.
If you could give us more information about what's happening vs what you expected to happen, that would really help.
When you use prepared statements, you can't set the values there.
You have to first prepare the statement using question marks and then set the parameters later.
Here is an example:
public void updateCoffeeSales(HashMap<String, Integer> salesForWeek) throws SQLException {
PreparedStatement updateSales = null;
PreparedStatement updateTotal = null;
String updateString = "update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement = "update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? where COF_NAME = ?";
try {
con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
updateSales.close();
updateTotal.close();
con.setAutoCommit(true);
}
}
SELECT * FROM q_table, choices, answers WHERE q_table.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'"
or
SELECT * FROM questions, choices, answers WHERE questions.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'"
That is not a proper prepareStatement. It's a concatenated query that will only lead you to sql injection horrors. Look here