Get row count of successful bulk insert using jdbc from sql server - java

I have Java code to bulk-insert tab file to SQL Server.
I want to get the count of how many records were inserted. I tried using ##rowcount but I'm getting an error that "Statement did not return a result set".
If I run the bulk insert statement in management studio, I can get the count.
Statement stmt = sqlConnection.createStatement();
ResultSet rs = stmt.executeQuery ("BULK INSERT schema1.table1 FROM 'd:\temp1\file1.tab' SELECT ##rowcount");
Is there any way to get the inserted count?

I'm not familiar with SQL Server but it seems like you'll want to issue an executeUpdate instead of an executeQuery
Statement stmt = sqlConnection.createStatement();
int insertedRowCount = stmt.executeUpdate("BULK INSERT schema1.table1 FROM 'd:\temp1\file1.tab'");

Related

error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? or tel=?' at line 1

Here's my query:
select *
from reg
where indexno=?
or tel=?
And here's my code:
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://url","unam","pass");
String query = "select * from reg where indexno= ? or tel=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, in.getText());
ps.setString(2, tl.getText());
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Let's take a closer look at what your code is doing.
Connecting to the database:
Connection con =DriverManager.getConnection("jdbc:mysql://url","unam","pass");
Creating the SQL query:
String query = "select * from reg where indexno= ? or tel=?"`;
Creating a prepared statement:
PreparedStatement ps = con.prepareStatement(query);
Setting some bind parameter values:
ps.setString(1, in.getText());
ps.setString(2, tl.getText());
Creating a whole new non-prepared statement (wait, what? Why are we not using the prepared statement we spent some time creating?):
Statement st = con.createStatement();
Using the new non-prepared statement to execute the SQL query.
ResultSet rs = st.executeQuery(query);
As a result of the last two lines, your SQL query is sent straight to the MySQL database. MySQL doesn't understand what the ? marks are for, and hence complains with a syntax error about them.
When handling prepared statements, JDBC drivers will either replace the ? marks with the database's own syntax for bind parameters (unless the database supports ? marks directly, but not all databases do), or put the values directly in the SQL string after suitable escaping of any characters, before they send the SQL to the database. Statements don't support bind parameters, and will just send the SQL string they are given straight to the database.
Your code creates a PreparedStatement and sets two bind parameter values. It seems a shame not to actually use your prepared statement once you've created it. You can get the result set you want out of it by calling ps.executeQuery(). There is no need for the separate Statement you created by calling connection.createStatement().
The fix therefore is to remove the last two lines of the code in your question and add the following line in place of them:
ResultSet rs = ps.executeQuery();

How to get the full query that a PreparedStatement is about to execute in DB2?

I'm working on a dynamic web project and using the PreparedStatement to execute the SQL queries against the DB2 database.
String myQuery = "select id from user where name = ?";
PreparedStatement stmt = connection.prepareStatement(myQuery);
stmt.setString(1, test);
ResultSet resultSet = statement.executeQuery();
How can I receive the full SQL query that is about to be executed on the DB2 server in the console?
If you are familiar with Debugging options in Eclipse. You may try the following:
Set a Breakpoint at ResultSet resultSet = statement.executeQuery();
Right click your application, say Debug As select Java Application (or Whatever applicable in your case i.e. may be SpringBoot App etc.
Perform step that gets you to code mentioned in the Question.
If you check Variables tab in Debug Perspective of Eclipse, you will find variables like myQuery , stmt (according to your code)
Whatever you see as value of stmt would be the full SQL query you need.
Also, if you don't want to keep looking at this variable always you may try Java Logging and Print your Full SQL query in Logs.

Update command with special SQL keywords in JDBC

I am trying a update an entry in my SQL table which has a column name "from" in JDBC.
Following is the SQL command that I am trying to execute:
sql = "Update email_template set [from]="+"'"+3+"'"+" WHERE id="+idno;
stmt.executeUpdate(sql);
However it shows the following error:
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 '[from]='Akshit' WHERE id=1' at line
MySQL's way of escaping column names is by using backticks:
sql = "Update email_template set `from`="+"'"+3+"'"+" WHERE id="+idno;
I recommend using java.sql.PreparedStatement when handling SQL in Java. It can be used for batches and ensures malicious SQL is not injected as part of the SQL code.
This is how your code looks with a PreparedStatement:
PreparedStatement stmt = connection.prepareStatement("UPDATE `email_template` SET `from` = ? WHERE id = ?");
stmt.setInt(1, 3);
stmt.setInt(2, idno);
stmt.executeUpdate();
If this is an operation you execute for many rows in one go, replace stmt.executeUpdate() with stmt.addBatch() (likely in some loop) and when you're ready to execute the batched updates you call stmt.executeBatch().
Note that both executeUpdate() and executeBatch() return how many rows were affected; which is something you may want to validate after a commit.

Setting work_mem in Postgres for specific queries

I'm using a library that delegates to a JDBC driver for PostgreSQL, and some queries are very complex and require more memory. I don't want to set work_mem to something large for all queries, just this subset. The problem is that executing the following code results in an error:
// pseudo-code for what is happening
String sql = "set work_mem = 102400;";
sql += "SELECT * FROM expensive_query";
ResultSet rs = DatabaseDriver.execute(sql);
When I run this I get an error that:
set work_mem = 102400;
returns no results.
This works in pgAdmin because you can execute multiple queries at once. Is there a better way to do this or do I need to execute arbitrary SQL and then extract the result set I want?
I have no idea what DatabaseDriver does, but with "plain" JDBC you just need to do the following:
Statment stmt = connection.createStatement();
stmt.execute("set work_mem = 102400");
ResultSet rs = stmt.executeQuery("select ...");
Try to do that using Batch Processing

get value from prepared statement query android?

i have a doubt that how to get the result of the prepared statement query in android.Actually i have a need that i want the row id from database while comparing a field words which can contain ' or" so i want to use prepared statement ,after googling out i did not get any proper example for android sqlite database ,please tell me how to use the prepared statement in android and after running query ,how to use value either through result set or through cursor.below is query look like-
String perfect_stmnt="select ID from Annotation where HighlightedWord=? ";
try{
** Connection con=DriverManager.getConnection("file:/"+ db.getPath());**
pstmt = con.prepareStatement(perfect_stmnt);
pstmt.setString(1, highlightword);
Resultset rs = pstmt.executeQuery();
Here the major doubt i am having how to get the connection here see the line having **
Thanks
The Android database API can prepare a statement (see compileStatement), but it is not possible to get a cursor or result set from that.
You can use compiled statements only if they return a single value, or nothing.
Please note that SQLite does not have a large overhead when preparing statements, so you can just call query or rawQuery multiple times.

Categories

Resources