[英]insert values into SQL database using JDBC
您好,我嘗試使用jdbc將值插入SQL數據庫。 當前代碼能夠連接和查詢sql DB。 我正在使用executeupdate插入值。此代碼未出現任何錯誤。但是值未插入SQL 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();
}
}
您已將autocommit
設置為false並且尚未提交。 您認為會發生什么? 來自Oracle自己的文檔 :
禁用自動提交模式后,在您顯式調用方法commit之前,不會提交任何SQL語句。
或者:
connection.setAutoCommit (true);
在創建連接時(盡管我們可以將其作為選項取消,因為您已將其顯式設置為false,這意味着您希望批量處理交易中的更改),或:
connection.commit();
從insertValues()
返回之前。
您可能還想檢查executeUpdate
的返回值,即使僅出於調試目的。 對於插入,它為您提供了插入的行數(在這種情況下,應為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文件)。 如果您使用任何IDE,請在Bulid路徑中。
插入后嘗試關閉連接,可能是數據保留在緩沖區中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.