JDBC SQL Server: Row doesn't appear after insert - java

I'm trying to insert rows on SQL Server using a JDBC driver.
The query works on SQL Server and I can see the row.
However, in my code, I don't get any error but the row doesn't appear.
What is even weirder, my auto-increment field is incremented, i.e. let's say my auto-increment field has value 3, I run my code, nothing appears. I run the query on SQLServer, the new row has value 5.
String query = "insert into SSSI_ADMIN.NBSIUSER(UserName,UserDomain) values('test4','domain4')";
Statement stmnt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
try {
Class.forName(driver);
String url = "jdbc:sqlserver://dt112654:1433;databaseName=SIBD;user=u;password=*****";
Connection conn = DriverManager.getConnection(url);
conn.setAutoCommit(false);
stmnt = conn.createStatement();
stmnt.execute(query);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if ( stmnt != null)
{
stmnt.close();
}
}
Regards,
Nuno.

You are not committing your change.
You have to call conn.commit() after stmnt.execute(query);

because this is code "conn.setAutoCommit(false);";one way to do this is "conn.setAutoCommit(true)" or delete this code "conn.setAutoCommit"; the other way to do this is after you execute the query you should add the another code "conn.commit()".

Related

How to save the results of a query on variables for each field on Java?

I need to accomplish the following:
1.- Save on different variables each field of a query result (Oracle DB).
The query result could be 1 o more rows (5 average).
2.- Invoke a WebService for each row.
4.- Wait for the WebService answer and then repeat the process.
I think that saving the result of 1 row and then invoke the WebService it easy but the problem is when the query result throws more than 1 row.
How can I do this? Is Arraylist the answer?
EDIT: I am using the following code. How can I print the arraylist to see if the connection is working?
If I run this i get:
com.packagename.SomeBean#1d251891
com.packagename.SomeBean#48140564
com.packagename.SomeBean#58ceff1
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List<SomeBean> v = new ArrayList<SomeBean>();
String query = "select * from table where ROWNUM BETWEEN 1 and 3";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:user/pass#localhost:port:SID");
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while( rs.next() ){
SomeBean n = new SomeBean();
n.setColumn1(rs.getInt("column1"));
n.setColumn2(rs.getString("column2"));
n.setColumn3(rs.getString("column3"));
n.setColumn4(rs.getInt("column4"));
n.setColumn5(rs.getString("column5"));
n.setColumn6(rs.getString("column6"));
n.setColumn7(rs.getString("column7"));
...
v.add(n);
}
for(SomeBean s : v){
System.out.println(s);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Answering to your question is quite difficoult.
But I can give you some hints.
Your startpoint is JDBC.
The Java Database Connectivity (JDBC)
The Java Database Connectivity (JDBC) API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases SQL databases and other tabular data sources, such as spreadsheets or flat files. The JDBC API provides a call-level API for SQL-based database access.
The Java Database Connectivity (JDBC)
Once you are able to establish a connection to the DB, this snippet can help you answering to your question.
// start connection
List<SomeBean> v = new ArrayList<SomeBean>();
Statement st;
try
{
st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while( rs.next() ){
SomeBean n = new SomeBean();
n.setFirstField(rs.getInt("firstfield"));
n.setSecondField(rs.getString("secondfield"));
...
...
v.add(n);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
// close connection
Once you have your collection of beans, just write a for loop that calls the webservice one time for each bean.
for(SomeBean s : v){
callToYouWS(s);
}

Insert data into mysql using java

This code hasn't error or exception, but after running the table features in the data base remain empty
try {
Class.forName("com.mysql.jdbc.Driver");
con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/sounds","root","");
statment = (Statement) con.createStatement();
String query = "INSERT INTO featuers (avg_Bandwidth) values (?)";
PreparedStatement preparedStmt = (PreparedStatement)con.prepareStatement(query);
preparedStmt.setDouble(1, avarage_Bandwidth);
preparedStmt.executeUpdate();
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Two things of note :
statment = (Statement) con.createStatement(); This variable is not used if I see it correctly. But this should not be the problem in itself
preparedStmt.executeUpdate(); This executeUpdate method should return a int based on the query itself. So it should return 1 in your case for the no of rows affected. So try to check what is returned.
This may not be the exact solutions but do try these and you may get some idea on what is happening
Hi try to use this one.
int status = 0; // to get the status to know if statement is executed properly or not
try {
Connection con = DBConnection.getConnect();//Your database Connection
Statement st = con.createStatement();
status = st.executeUpdate(query); //After executing this it will return an int value
} catch (Exception ex) {
ex.printStackTrace();
}
I hope this will help you.

Why I didn't get results when adding Where clause to my query?

I'm using Mysql JDBC driver.. but I have some problem..
the problem is when I use SELECT Query in java source code.
When I use this query:
select * from [name of table]
I've gotten result of query from DB successfully.
but when I use this query:
select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ;
I've not gotten result of query from DB..
The difference thing is just that using where or not.
What's the problem?
How can I solve this problem?
this is my code below
this query isn't working
select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ;
this query is working very well
select * from student;
The difference thing is just only query information .. rest of the source code is the same absolutely
I added my java source code
public class Center {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String sql = "select * from student where (substring(stu_name,0,1)>= '가' and substring(stu_name,0,1) < '나') ";
String url = "jdbc:mysql://localhost:3306/test";
String driverName = "com.mysql.jdbc.Driver";
String id = "root";
String password = "jsyun0415";
Connection con = null;
PreparedStatement prepareState = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list_second = new ArrayList<String>();
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
System.out.println("Failed to load JDBC driver..");
e.printStackTrace();
return;
}
try {
con = DriverManager.getConnection(url, id, password);
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
list.add(rs.getNString("stu_no"));
list_second.add(rs.getNString("stu_ename"));
}
//test = list.get(2);
} catch (SQLException sqex) {
System.out.println("SQLException: " + sqex.getMessage());
System.out.println("SQLState: " + sqex.getSQLState());
} finally {
try {
if (stmt != null)
stmt.close();
if (con != null)
con.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You will need to set the the character encoding in the JDBC connection URL:
String url = "jdbc:mysql://localhost:3306/test?useUnicode=yes&characterEncoding=UTF-8";
Otherwise the character encoding between client and server is automatically detected upon connection, this means that the Korean text in your query will be wrongly encoded and will probably cause the query to return zero results.
You can read more about this in the MySQL JDBC driver documentation - Using Character Sets and Unicode
This answer suggests that there's no problem with the Java code; it's your data.
Can you run the query in the MySQL admin tool and get back a result set that's not empty? If yes, there's a problem with your Java code. There must be an error that you either aren't supplying or you swallow with an empty catch block.
Do you get an error message or stack trace, or is the result set empty? If it's the latter, perhaps there is no student row with number 20001001.
MySQL function "substring" parameter 0 is wrong, only more then zero allowed.

How to call Stored Procedure and prepared statement

In the below code I want to call one stored procedures and execute one Query. I am facing error at statement.executeUpdate(); Please help in fixing it. I am not sure where it going wrong.
public void Dbexe() {
Connection connection;
connection = DatabaseConnection.getCon();
CallableStatement stmt;
try {
stmt = connection.prepareCall("{CALL optg.Ld_SOpp}");
stmt.executeUpdate();
stmt.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Stored Procedure executed");
//PreparedStatement statement = null;
// ResultSet rs = null;
try{
PreparedStatement statement;
try {
statement = connection.prepareStatement("MERGE INTO OPTG.R_VAL AS TARGET USING" +
........... +
"");
statement.executeUpdate(); //Here the exception is thrown
statement.close();
connection.commit();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// statement = connection.prepareStatement(query);
//statement.close();
}
finally{
System.out.println("Data is copied to the Table");
}
}
Little off-topic: You should use CallableStatement instead if you want to call a store procedure (see documentation):
CallableStatement callableStatement = connection.prepareCall("{call opptymgmt.Load_SiebelOpportunity}");
ResultSet rs = callableStatement.executeQuery();
I would also suggest you check this topic How to properly clean up JDBC resources in Java?. It was very helpful to me.
Update: based on this stack trace:
com.ibm.db2.jcc.am.mo: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=MERGE INTO OPPTYMGMT.REVENUE_VALIDAT;BEGIN-OF-STATEMENT;<variable_set>, DRIVER=4.7.85
The problem seems to be in the sql sentence you're trying to execute. I mean, is an error from DB2, not java. You should check your sql statement.
I got it working in this method:
PreparedStatement myStmt = conn.prepareStatement(sqlQuery);
myStmt.setInt(1, id); //position of parameter (1,2,3....) , value
ResultSet rs = myStmt.executeQuery();
while (rs.next()) {
int jobId = rs.getInt("jobId"); ....... }

why does executeUpdate return 1 even if no new row has been inserted?

here is my very simple table (Postgres):
CREATE TABLE IF NOT EXISTS PERFORMANCE.TEST
(
test text NOT NULL UNIQUE
);
if I try to insert a String using the command below FROM the database,everything works as expected, not surprisingly a new row appears in the DB.
insert into performance.test (test) values ('abbbbaw');
However if I want to insert a String through JDBC, nothing gets inserted, although preparedStatement.executeUpdate() always returns 1.
Below is my method that should be working but it does not. Please tell me if I am missing something obvious.
I want to add that I never get any SQLException.
private void storePerformance() {
Connection conn= initializePerformanceConnection();
if (conn!= null) {
PreparedStatement insertPS = null;
try {
insertPS = conn.prepareStatement("insert into performance.test (test) values (?)");
insertPS.setString(1, queryVar);
int i = insertPS.executeUpdate();
LogManager.doLog(LOG, LOGLEVEL.INFO," numberofrows= "+i);
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Inserting query failed = "+queryVar,e);
}finally{
if(insertPS != null){
try {
insertPS.close();
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Closing PreparedStatement failed = "+queryVar,e);
}
}
try {
conn.close();
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Closing performanceConnection failed= "+ queryVar, e);
}
}
}
}
that was missing:
conn.commit();
(after the executeUpdate())
actually a new row was inserted but the DB rolled back immediately.
executeupdate is for a 'update table set column = value so on'. For insert just call execute of PreparedStatement.

Categories

Resources