Mysql -Issue with preparedStatement insert query - java

I have a table in a MySQL database which is 2 columns,
String insertquery = "INSERT INTO Table (Col1, Col2) VALUES (?, ?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertSQL);
preparedStatement.setString(1, "Val 1");
preparedStatement.setString(2, "Val 2");
preparedStatement.executeUpdate();
The thing is that the second column values decide at run time, where to insert value or keep default.
how to set setString as default .
preparedStatement.setString(2, default );
or can i write two seperate sql depends upon condition ? is there any way to handle this senario?
same issue for update sql.
String updatequery = "UPDATE Table SET Col1=?, Col2=?;"
PreparedStatement preparedStatement = dbConnection.prepareStatement(updatequery);
preparedStatement.setString(1, "Val 1");
preparedStatement.setString(2, "Val 2");
preparedStatement.executeUpdate();
I am able to set like this
preparedStatement.setNull(2, '');
I have to kept old value as it is, not update as null
Thank you...

To achieve this, you have to leave out the column name and MySQL will then use the default value for any column names that have been omitted.
So when you want the value of Col2 to be the default, then you would write your query like so:
"INSERT INTO Table (Col1) VALUES (?)";
I think your best choice is to actually prepare the statement itself at run-time based on the columns that you want to change.
I'm not really sure how easily this can be done in Java but with PHP this could be done so easily by having an array of column names and adding/removing items off the array at run-time depending on what columns needs to be updated and then using the PHP Implode function to glue each item of the array with a comma and finally concatenating the resulting string to your final query.
Maybe you might be able to find solutions that are more suited for java by reading through this related stack-overflow answer.
Good luck

Related

Error in inserting commands in SQL databases using java

I need to update the sql database daily manner for changes in clicks impressions and conversions column. i had array for each column. In this statement there is a error . i cant find the error too.help please
for(int j=1;j<row;j++){
pst= conn.prepareStatement("INSERT INTO babum_test.l2ttracker SET Clientid='"+Customer_ID[j]+"',Accountname='"+Account[j]"',Dates='"Day[j]"',Clicks='"Clicks[j]"',Impressions='"Impressions[j]"',CTR='"CTR[j]"',Avg_CPC='"Avg_CPC[j]"',Cost='"Costs[j]"',Conversions='"Conversions[j]"',Converted_clicks='"Converted_clicks[j]"',Avg_position='"Avg_position[j]"',Revenue='"Total_Conv_value[j]+"' ON DUPLICATE KEY UPDATE'"+ "'Clicks='"+Clicks[j]"',Impressions='"Impressions[j]"',CTR='"CTR[j]"',Avg_CPC='"Avg_CPC[j]"',Cost='"Costs[j]"',Conversions='"Conversions[j]"',Avg_position='"Avg_position[j]"',Converted_clicks='"Converted_clicks[j]"',Revenue='"Total_Conv_value[j]);
}
Three main problems there:
You're not using quotes where you should be using quotes.
I'm not aware of any database that uses an INSERT ... SET statement.
You're leaving yourself wide open to SQL Injection attacks.
Obligatory comic re #3:
Instead:
pst = conn.prepareStatement(
"INSERT INTO sampletable " +
"(FirstColumn SecondColumn, Etc) " +
"VALUES " +
"(?, ?, ?)"
);
pst.setString(1, "value for first column");
pst.setInt(2, 42);
pst.setDate(3, /*...some date...*/);
pst.execute();
The question marks are placeholders where the prepared statement will put the values. Even when the parameter is a string, you don't put quotes around the question mark; that's handled behind the scenes and is part of the reason for using prepared statements. Note that the parameter numbers start at 1, not 0.
Read up on SQL syntax and how to correctly use prepared statements; this site may be useful.

Inserting data into Multiple tables

String insert1 = "INSERT INTO Table1(Col1, col2, col3)"
+ "VALUES(?,?,?)";
String insert2 = "INSERT INTO Table2(Colx, coly)"
+ "VALUES(?,?)";
Connection conn = aConn;
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(insert1);
// ps.addBatch(insert2);
I'm trying to Insert Data into multiple tables at a time, and it seems like addBatch(String sql) is not defined for PreparedStatement.
Is there any alternate way?
First of all, a PreparedStatement is used to cache a single SQL statement. This has the advantage that the driver/database might optimize the statement since it is expecting many of them and since it is a parameterized statement. If you want to use it for two different SQL statements you need two PreparedStatements.
In order to add rows to the statement you need to set your parameters using set*(1,...), set*(2,...), set*(3,...), etc. and then call addBatch() (no arguments!). Finally you submit the batch of statements using executeBatch().

Inserting variables with SQL in Java

I'm writing a webpage that takes input from a form, sends it through cgi to a java file, inserts the input into a database through sql and then prints out the database. I'm having trouble inserting into the database using variables though, and I was wondering if anyone would be able to help me out.
String a1Insert = (String)form.get("a1");
String a2Insert = (String)form.get("a2");
This is where I get my variables form the form (just believe that it works, there's a bunch more back end but I've used this before and I know it's getting the variables correctly).
String dbURL = "jdbc:derby://blah.blahblah.ca:CSE2014;user=blah;password=blarg";
Connection conn = DriverManager.getConnection(dbURL);
Statement stmt = conn.createStatement();
stmt.executeUpdate("set schema course");
stmt.executeUpdate("INSERT INTO MEMBER VALUES (a1Insert, a2Insert)");
stmt.close();
This is where I try to insert into the databse. It give me the error:
Column 'A1INSERT' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'A1INSERT' is not a column in the target table.
If anyone has any ideas that would be lovely ^.^ Thanks
java.sql.Statement doesn't support parameters, switching to java.sql.PreparedStatement will allow you to set parameters. Replace the parameter names in your SQL with ?, and call the setter methods on the prepared statement to assign a value to each parameter. This will look something like
String sql = "INSERT INTO MEMBER VALUES (?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "a1");
stmt.setString(2, "a2");
stmt.executeUpdate();
That will execute the SQL
INSERT INTO MEMBER VALUES ('a1', 'a2')
Notice the parameter indexes start from 1, not 0. Also notice I didn't have to put quotes on the strings, the PreparedStatement did it for me.
Alternatively you could keep using Statement and create your SQL string in Java code, but that introduces the possibility of SQL injection attacks. Using PreparedStatement to set parameters avoids that issue by taking care of handling quotes for you; if it finds a quote in the parameter value it will escape it, so that it will not affect the SQL statement it is included in.
Oracle has a tutorial here.

Update and delete in oracle using java

I have a table named bcfsite with a field named activestate.
update bcfsite set activestate = 1 where bscname like '%B361Z%'
When I run the above query SQLPlus or Oracle SQL Developer, it works fine without any problems, but when I run it in Java using this code:
String sqlstrString = "update bcfsite
set activestate = 0 where bscname like '%B361Z%' ";
PreparedStatement ps = d.prepareStatement(sqlstrString);
ResultSet rs = ps.executeUpdate();
or this code :
ResultSet rs = DBConnection.RunStatement(sqlstrString, d);
My program pends and doesn't pass the update statement.
I changed the table and column and tried delete instead of update but still I see the same problem.
I am putting this is the answer box because there is not enough room in the comments...
String qString = "update bcfsite set activestate = 0 where bscname like ?";
That is the correct way to do this with a replaceable parameter. Remember when using the like operator everything passed to it is a varchar2 as far as oracle is concerned so:
ps.setString(1,"%B361Z%");
Again, this is the correct way to accomplish this.
The resulting string passed to oracle via jdbc will look like:
update bcfsite set activestate = 0 where bscname like '%B361Z%'
setString() applies the correct markup so the oracle query parser will see a correct query.
Queries with a "?" in them are not simply string replaced. The statement is parsed by the server, and then the parameter(s) are passed to the server.
BTW this was answered in several places on SO. Please learn how to search SO and it will shorten your response time considerably and not waste our time.
Can you try following approach first to clear out it updates atleast one row through Java code, don't give wild characters try to update single row.
String sqlstrString = "update bcfsite
set activestate = 0 where bscname=?";
PreparedStatement ps = d.prepareStatement(sqlstrString);
ps.setString(1, "B361Z");
ResultSet rs = ps.executeUpdate();
This may rule out other issues like connectivity/different schema ..
Please post the result.
Try this approach:
String sqlstrString = "update bcfsite " +
"set activestate = 0 where bscname like '?'";
PreparedStatement ps = d.prepareStatement(sqlstrString);
ps.setString(1, "%"+"B361Z"+"%");
ResultSet rs = ps.executeUpdate();
And a second approach would be:
...set activestate=0 where bscname like CONCAT('%', ?, '%')";
...
ps.setString(1, "B361Z");

Prepared statement with wildcard not returning certain rows but query returns all rows?

I'm using JTDS as a driver to connect to SQL server.
Here's the query that's giving me problems:
SELECT EmpID,FirstName,LastName,CompanyName,DepartmentName,JobTitle,HireDate FROM Employees where UPPER(FirstName) LIKE 'KEVIN%'
It returns 2 rows on SQL Server. One that has 'KEVIN' in upper case and another that has 'Kevin' like so. I used the wildcard to make sure I get both results. In my EmployeeDAO class I'm using the following:
ps = con.prepareStatement("SELECT EmpID,FirstName,LastName,CompanyName,"
+ "DepartmentName,JobTitle,HireDate FROM Employees WHERE UPPER(FirstName) LIKE ?");
ps.setString(1, FirstName + "%");
rs = ps.executeQuery();
And then of course I put KEVIN on my main. It only returns ONE row, which is the 'Kevin' row.
How do I fix this so it returns all rows?
Your query looks fine (although I would uppercase the parameter value before setting it, to make it more robust). The problem is just in the way how you're collecting the rows from the ResultSet. Likely you're plain overriding the previous row with the next row so that you end up with only one row (the last one) in your collection.
Default collation of the SQL Server installation is SQL_Latin1_General_CP1_CI_AS and it is not case sensitive.
Change collation of the query:
SELECT Col1
FROM Table1
WHERE Col1 COLLATE Latin1_General_CS_AS LIKE 'KEVIN%'

Categories