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
Related
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.
I want to move to the other frame if the query result is empty. How can I check if the query is empty?
String query2 ="Select* from biletbilgileri where FilminÄ°smi='" + filmKoltuk + "'" +
" " + "and" + " " + "SeansTarihi='" + SeansTarihKoltuk + "'" + " " + "and" + " " +
"SeansSaati='" + SeansSaatKoltuk + "'";
Statement stmt1=conn.createStatement();
ResultSet rs1=stmt1.executeQuery(query2);
rs1.next();
if(rs1==null)
{
tesekkurEkrani1.setVisible(true);
tesekkurEkrani1.setSize(1000,500); }
else {
JOptionPane.showMessageDialog(null, "This chair isn't empty!");
}
You want to use SQL count(*) in the query select count(*) from biletbilgileri .... If the returned value is 0, there are no rows returned by your original query.
String query2 = "select count(*) from biletbilgileri ...";
ResultSet rs1 = stmt1.executeQuery(query2);
rs1.next();
int count = rs1.getInt(1);
if (count == 0) {
// empty
}
When you call rs1.next();, it returns a boolean. If the boolean is false, it means there are no more rows. so I think you want to do this:
boolean notEmpty = rs1.next();
if(notEmpty )
{
I am inserting a row in Java Derby Embedded database. Immediately I am rechecking whether the row with the particular ID exists. The code I use works fine elsewhere in Sqlite3, MySql etc. But in Derby it throws an error, invalid cursor state, no current row.( But the row is added and exists) What is that I am doing wrong?
String sql="";
stmt = conn.createStatement();
sql = "INSERT INTO USERLIST (UserID,UserName,PaWord,RealName) " +
"VALUES (" + Nextam + ",'" + f1 + "','" + f2 + "','" + f3 + "')";
stmt.executeUpdate(sql);
stmt.close();
Thread.sleep(1000);
// rechecking
stmt = conn.createStatement();
rs = stmt.executeQuery( "SELECT * FROM USERLIST where UserID=" + Nextam + "" );
String nameR = rs.getString("RealName");
if(nameR.length() < 2){
System.out.println( "Seems like Error " + Nextam );
}else{
String infum=nameR + " Added as " + Nextam;
ShowLab(infum);
}
stmt.close();
conn.close();
You didn't call rs.next() after you performed the stmt.executeQuery() call.
Are you sure this code works on other systems?
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.