Reputation: 73
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();
}
}
Upvotes: 0
Views: 22646
Reputation: 881153
You've set autocommit
to false and haven't committed. What did you think would happen? From Oracle's own docs on the subject:
After the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly.
Either:
connection.setAutoCommit (true);
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:
connection.commit();
before returning from insertValues()
.
You may also want to check the return value from executeUpdate
even if only for debugging purposes. For an insert, it gives you the number of rows inserted (should be one, in this case).
Upvotes: 4
Reputation: 1187
just try with this example :
this is working one..
import java.sql.*;
public class InsertValues{
public static void main(String[] args) {
System.out.println("Inserting values in database table!");
Connection con = null;
String url = "jdbc:jtds:sqlserver://127.0.0.1:1433/Example";
String username = "sa";
String password = "";
String driver = "net.sourceforge.jtds.jdbc.Driver";
try{
Class.forName(driver);
con = DriverManager.getConnection(url,username,password);
try{
Statement st = con.createStatement();
int val = st.executeUpdate("insert into dbo.Company " +"values('abc', 2)");
System.out.println("1 row affected");
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
NB: you must added the sql driver (Dricer jar file) in your class path. if you are using any IDE, in your Bulid path.
Upvotes: 0
Reputation: 415
Try closing the connection after insertion, may be the data is kept in buffer
Upvotes: 0