hi am trying to insert values into SQL database using jdbc. Current code able to connect and query sql DB. am using executeupdate to insert the values .this code is not giving any errors.but values are not getting inserted into SQL DB. how can i insert values into DB???
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import com.microsoft.sqlserver.jdbc.SQLServerException;
import java.sql.*;
import java.sql.Connection;
class New{
Connection connection = null;
void condb() throws SQLServerException, SQLException{
SQLServerDataSource dataSource = new SQLServerDataSource();
dataSource.setServerName("OEl");
dataSource.setPortNumber(1433);
dataSource.setDatabaseName("Example");
dataSource.setUser("sa");
dataSource.setPassword("******");
connection = dataSource.getConnection();
connection.setAutoCommit(false);
System.out.println("Connected to server !!!");
}
void insertvalues() throws SQLException{
Statement statement1=connection.createStatement();
statement1.executeUpdate("insert into dbo.Company " +
"values('abc', 2)");
}
public static void main(String args[]) throws SQLServerException, SQLException{
New con=new New();
con.condb();
con.insertvalues();
}
}
You’ve set
autocommitto false and haven’t committed. What did you think would happen? From Oracle’s own docs on the subject:Either:
when you create the connection (although we can probably discount that as an option since you explicitly set it to false, meaning you wanted to batch up your changes in a transaction), or:
before returning from
insertValues().You may also want to check the return value from
executeUpdateeven if only for debugging purposes. For an insert, it gives you the number of rows inserted (should be one, in this case).