您正在尝试使用jdbc将值插入SQL数据库。当前代码能够连接和查询sql DB。我正在使用executeupdate来插入值。这段代码没有给出任何错误。但是值没有插入到SQL DB中。如何将值插入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();
}
}
答案 0 :(得分:4)
您已将autocommit
设置为false并且尚未提交。您认为会发生什么?来自Oracle's own docs on the subject:
禁用自动提交模式后,在您明确调用commit 方法之前,不会提交任何SQL语句。
或者:
connection.setAutoCommit (true);
当您创建连接时(虽然我们可以将其作为选项折扣,因为您明确将其设置为false,这意味着您想要批量处理事务中的更改),或者:
connection.commit();
从insertValues()
返回之前。
您可能还想检查executeUpdate
的返回值,即使仅用于调试目的。对于插入,它会为您提供插入的行数(在本例中应为1)。
答案 1 :(得分:1)
试试这个例子:
这是一个......
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();
}
}
}
注意:您必须在类路径中添加sql驱动程序(Dricer jar文件)。 如果您在Bulid路径中使用任何IDE。
答案 2 :(得分:0)
尝试在插入后关闭连接,可能是数据保存在缓冲区中