Insert data into mysql using java - 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.

Related

How to store output of MySQL command into a java variable (JDBC)

I was wondering how to issue a MySQL command that checks if a table within my database is empty and then subsequently store the boolean result into a java variable. I am trying to use JDBC commands to do this.
This is what I have so far but it is not working properly:
#Override
public boolean isEmpty(Connection connection) {
Statement statement = null;
ResultSet resultSet = null;
Boolean var = true;
try {
statement = connection.createStatement();
System.out.println(statement.execute("SELECT EXISTS (SELECT 1 FROM Persons) AS OUTPUT"));
if(statement.execute("SELECT EXISTS (SELECT 1 FROM Persons)")) {
var = false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return var;
}
When I run the program with a completely new, unpopulated mySQL table, the function returns true. Does anyone know a solution?
Your test checks if the table exists, instead you want to see if the table contains any rows. In order to do so, select the count of rows from the table and verify it is greater than 0. Prefer PreparedStatement over Statement (it's more efficient and performant), and you need a ResultSet to actually iterate the result from the server. Something like,
#Override
public boolean isEmpty(Connection connection) {
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean res = false; // no need for the wrapper type here.
String sql = "SELECT COUNT(*) FROM Persons";
try {
statement = connection.prepareStatement(sql);
System.out.println(sql);
resultSet = statement.executeQuery();
if (resultSet.next()) {
res = resultSet.getInt(1) > 0;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return res;
}
Changed var to res because (as of Java 10) var is now a keyword in Java.
As you are executing a select statement, instead of using Statement.execute(..), you should use Statement.executeQuery(..) and iterate over its result set.
The boolean return value from execute(..) indicates if the first value is a result set or not. It is not the boolean column from your query. You should normally only use execute(..) if you don't know what type of statement it is, or if it is a statement that can produce multiple results (update counts and result sets).
So, instead use:
boolean exists;
try (ResultSet rs = statement.executeQuery("SELECT EXISTS (SELECT 1 FROM Persons)")) {
exists = rs.next() && rs.getBoolean(1);
}

ResultSet giving me the first row only

I'm trying to read string values from my database to insert them in an arraylist of strings. However, my loop stops after completing only one row.
That's my code,
public void initialize(URL arg0, ResourceBundle arg1) {
Statement stmt = null;
String query = "SELECT CustomerName FROM CUSTOMER WHERE CustomerName IS NOT NULL";
try {
Connection conn1 = DBConnection.getConnection();
stmt = conn1.createStatement();
ResultSet rs = stmt.executeQuery(query);
// iterate through the java resultset
while (rs.next()) {
System.out.println(rs.getString("CustomerName"));
customersnames.add(rs.getString("CustomerName"));
}
stmt.close();
} catch (Exception e) {
System.out.println("Exception at initialize ");
System.err.println(e.getMessage());
}
try {
TextFields.bindAutoCompletion(customer, customersnames);
} catch (NullPointerException E) {
}
}
and that's what I'm getting
null (that's in red)
heee
Exception at initialize
"heee" is the first row of my database, but I have many more, that's what it's reading only and it's throwing an exception.
Apparently, you get a NullPointerException after having printed the result of the first row.
Did you initialize your object customersnames?
In order to be sure, change System.err.println(e.getMessage()); into e.printStackTrace()

Connection to SqlServer not closing in for loop java

I'm not sure the best practice for this, but my overall problem is that I can't figure out why my connection isn't closing.
I'm basically iterating through a list, and then inserting them into a table. Before I insert them into a table, I check and make sure it's not a duplicate. if it is, I update the row instead of inserting it. As of now, I can only get 13 iterations to work before the debug lets me know I had a connection not close.
Since I have 2 connections, I'm having trouble figuring out where I'm suppose to close my connections, and I was trying to use other examples to help. Here is what I got:
Connection con = null;
PreparedStatement stmt = null;
PreparedStatement stmt2 = null;
ResultSet rs = null;
Connection con2 = null;
for (Object itemId: aList.getItemIds()){
try {
con = cpds2.getConnection();
stmt = con.prepareStatement("select [ID] from [DB].[dbo].[Table1] WHERE [ID] = ?");
stmt.setInt(1, aList.getItem(itemId).getBean().getID());
rs = stmt.executeQuery();
//if the row is already there, update the data/
if (rs.isBeforeFirst()){
System.out.println("Duplicate");
stmt2 = con2.prepareStatement("UPDATE [DB].[dbo].[Table1] SET "
+ "[DateSelected]=GETDATE() where [ID] = ?");
stmt2.setInt(1,aList.getItem(itemId).getBean().getID());
stmt2.executeUpdate();
}//end if inserting duplicate
else{
con2 = cpds2.getConnection();
System.out.println("Insertion");
stmt.setInt(1, aList.getItem(itemId).getBean().getID());
//Otherwise, insert them as if they were new
stmt2 = con.prepareStatement("INSERT INTO [DB].[dbo].[Table1] ([ID],[FirstName],"
+ "[LastName],[DateSelected]) VALUES (?,?,?,?)");
stmt2.setInt(1,aList.getItem(itemId).getBean().getID() );
stmt2.setString(2,aList.getItem(itemId).getBean().getFirstName());
stmt2.setString(3,aList.getItem(itemId).getBean().getLastName() );
stmt2.setTimestamp(4, new Timestamp(new Date().getTime()));
stmt2.executeUpdate();
}//End Else
}catch(Exception e){
e.printStackTrace();
}//End Catch
finally{
try { if (rs!=null) rs.close();} catch (Exception e) {}
try { if (stmt2!=null) stmt2.close();} catch (Exception e) {}
try { if (stmt!=null) stmt.close();} catch (Exception e) {}
try { if (con2!=null) con2.close();} catch (Exception e) {}
try {if (con!=null) con.close();} catch (Exception e) {}
}//End Finally
} //end for loop
Notification.show("Save Complete");
This is my pooled connection:
//Pooled connection
cpds2 = new ComboPooledDataSource();
try {
cpds2.setDriverClass("net.sourceforge.jtds.jdbc.Driver");
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //loads the jdbc driver
cpds2.setJdbcUrl( "jdbc:jtds:sqlserver://SERVERNAME;instance=DB" );
cpds2.setUser("username");
cpds2.setPassword("password");
cpds2.setMaxStatements( 180 );
cpds2.setDebugUnreturnedConnectionStackTraces(true); //To help debug
cpds2.setUnreturnedConnectionTimeout(2); //to help debug
My main questions are, am i closing my connections right? Is my connection pool set up right?
Should I be closing the connection inside the for loop or outside?
Is my problem with c3p0? Or JTDS?
It's great that you are working to be careful to robustly close() your resources, but this is overly complicated.
Unless you are using a pretty old version of Java (something prior to Java 7) you can use try-with-resources, which really simplifies this stuff. Working with two different Connections in one logic unit-of-work invites misunderstandings. Resources should be a close()ed as locally to their use as possible, rather than deferring everything to the end.
Your Exception handling is dangerous. If an Exception occurs that you don't understand, you might want to print its stack trace, but your code should signall the fact that whatever you were doing didn't work. You swallow the Exception, and even notify "Save Complete" despite it.
All this said, your life might be made much easier by a MERGE statement, which I think SQL Server supports.
Here is an (untested, uncompiled) example reorganization:
try ( Connection con = cpds2.getConnection() ) {
for (Object itemId: aList.getItemIds()){
boolean id_is_present = false;
try ( PreparedStatement stmt = con.prepareStatement("select [ID] from [DB].[dbo].[Table1] WHERE [ID] = ?") ) {
stmt.setInt(1, aList.getItem(itemId).getBean().getID());
try ( ResultSet rs = stmt.executeQuery() ) {
id_is_present = rs.next();
}
}
if ( id_is_present ) {
System.out.println("Duplicate");
try ( PreparedStatement stmt = con.prepareStatement("UPDATE [DB].[dbo].[Table1] SET [DateSelected]=GETDATE() where [ID] = ?") ) {
stmt.setInt(1,aList.getItem(itemId).getBean().getID());
stmt.executeUpdate();
}
} else {
System.out.println("Insertion");
try ( PreparedStatement stmt = con.prepareStatement("INSERT INTO [DB].[dbo].[Table1] ([ID],[FirstName], [LastName],[DateSelected]) VALUES (?,?,?,?)") ) {
stmt.setInt(1,aList.getItem(itemId).getBean().getID() );
stmt.setString(2,aList.getItem(itemId).getBean().getFirstName());
stmt.setString(3,aList.getItem(itemId).getBean().getLastName() );
stmt.setTimestamp(4, new Timestamp(new Date().getTime()));
stmt.executeUpdate();
}
}
}
Notification.show("Save Complete");
}

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"); ....... }

JDBC SQL Server: Row doesn't appear after insert

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()".

Categories

Resources