I can't insert both values in different SQL tables - java

I used this code for my controller to insert values into tables.
public boolean createDuty() throws ParseException{
boolean success = false;
DBController db = new DBController();
String dbQuery;
db.getConnection();
dbQuery = "INSERT INTO duty(dutyName)" + " VALUES ('" + dutyName + "')";
dbQuery = "INSERT INTO venue(venueAddress)" + " VALUES ('" + venueAddress + "')";
if (db.updateRequest(dbQuery) == 1){
success = true;
}
db.terminate();
return success;
}
However, the output from java only says that only the venueAddress has been inserted and not the dutyName.
Successfully connected to jdbc:mysql://xxxxx/xxxxx.
DB Query: INSERT INTO venue(venueAddress) VALUES ('Woodgrove Tennis Centre')
Connection is closed
Is there something wrong with my codes? Can someone pls help me..

Read your code:
dbQuery = "INSERT INTO duty(dutyName)" + " VALUES ('" + dutyName + "')";
Here you're assigning a SQL query to the variable dbQuery. Then
dbQuery = "INSERT INTO venue(venueAddress)" + " VALUES ('" + venueAddress + "')";
Here you're assigning another SQL query to the same variable. Then
if (db.updateRequest(dbQuery) == 1){
Here you're executing the query referenced by dbQuery. If you want to execute 2 queries, you need to call db.updateRequest() twice once with the first SQL query, and once with the second one.
Also, read about prepared statements. Your code is vulnerable to SQL injection attacks, and will break as soon as venueAddress or dutyName contains a single quote.

you only execute the second query:
change:
dbQuery = "INSERT INTO duty(dutyName)" + " VALUES ('" + dutyName + "')";
dbQuery = "INSERT INTO venue(venueAddress)" + " VALUES ('" + venueAddress + "')";
if (db.updateRequest(dbQuery) == 1){
success = true;
}
to:
dbQuery = "INSERT INTO duty(dutyName)" + " VALUES ('" + dutyName + "');";
dbQuery += "INSERT INTO venue(venueAddress)" + " VALUES ('" + venueAddress + "')";
if (db.updateRequest(dbQuery) == 1){
success = true;
}
You have to add a ";" ad end of statement one.
Also you have to concat both strings.

Related

inserting to database using java gui

I am trying to insert data from my netbeans to mysql workbench. there is no problem with the query but when I run the program a message box appear "Unknown column 'empJob' in 'field list '" . What seems to be the problem?
and just to Know i tried this on another table and it works just fine! but in this one it doesn't work!
int id, Salary;
String name, Address, Jop;
id = Integer.parseInt(tNo.getText());
name = tName.getText();
Address = tAddress.getText();
Jop = tJop.getText();
Salary = Integer.parseInt(tNo.getText());
String sql = "insert into employee(empid,empName, empAddress,empJob,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int x = st.executeUpdate(sql);
if (x > 0) {
JOptionPane.showMessageDialog(prev, x + "rows effected");
} else {
JOptionPane.showMessageDialog(prev, "insert failed");
}
Do you have a typo? You write empJob -> but your variable is called Jop. So maybe it should be empJop.
String sql = "insert into employee(empid,empName, empAddress,empJop,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";

How do I insert local variable MySQL using JDBC

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.

Java Embedded, after insert I cannot recheck if the row exists

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?

Multipe Queries and ResultSets stored in one ArrayList

I'm trying to store multiple ResultSets into one ArrayList. I'm catching an error on my while-loop at the first ResultSet.
Here's my code:
List<String> target= new ArrayList<String>();
try{
wpCall.Connect("database");
wpCall.ResetParms();
sql = "SELECT column";
sql += "FROM table";
sql += "WHERE col2= 'val1'";
sql += "AND col3= 'field2'";
ResultSet rst1 = wpCall.GetResult(sql);
while(rst1.next()) {
String values= rst1.getString(1);
target.add(values);
}
wpCall.Connect("database");
wpCall.ResetParms();
sql = "SELECT column";
sql += "FROM table";
sql += "WHERE col2= 'val2'";
sql += "AND col3= 'field2'";
ResultSet rst1 = wpCall.GetResult(sql);
while(rst1.next()) {
String values2= rst1.getString(1);
target.add(values2);
}
}
finally {
System.out.print("Values: " + Target+ "\n");
}
Thanks for any help!
Your SQL is malformed, you have missed some spaces:
Your first statement should be:
sql = "SELECT column";
sql += " FROM table";
sql += " WHERE col2= 'val1'";
sql += " AND col3= 'field2'";
And your second statement should be:
sql = "SELECT column";
sql += " FROM table";
sql += " WHERE col2= 'val2'";
sql += " AND col3= 'field2'";

Insert query - executeUpdate returning -1

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.

Categories

Resources