如何使用JDBC创建表并将记录INSERT到表中?

时间:2017-02-15 04:53:18

标签: java sql-server database jdbc

我试图使用JDBC一次执行多个SQL语句。我知道addBatch()和executeBatch()函数可用于实现此目的。我已将它们合并到我的代码中甚至“SET NOCOUNT OFF”但我的CREATE和INSERT语句没有反映在我的SQL Server数据库中。以下是我在下面尝试的内容:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.microsoft.sqlserver.jdbc.SQLServerException;

public class Excel_Java_POI_Exp_V2 
{
    @BeforeClass
    public void setUp() throws Exception 
    {
        //Do Nothing
    }

    @Test
    public void testUsingExcel() throws Exception, SQLException
    {
        String url = "jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks2012;" + "integratedSecurity=true;";

        try
        {
            //Loading the required JDBC Driver class
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  

            //Creating a connection to the database
            Connection conn = DriverManager.getConnection(url);

            //Print Connection Verification
            System.out.println("Connection Established ln");

            Statement query = conn.createStatement();

            //Executing SQL query and fetching the result
            String SQL = "SET NOCOUNT OFF;";

            //CREATE A NEW SQL TABLE AFTER ESTABLISHING CONNECTION
            String SQL_Create = "CREATE TABLE SELCREATEDB"
                          + "(PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255));";

            //INSERT 10 RECORDS WITHIN DATABASE TABLE
            String SQL1 = "INSERT INTO dbo.SELCREATEDB VALUES "
                          + "(\"1000\", \"Davis\", \"John\", \"3444 Mulberry Lane\", \"Oakland CA\")";

            String SQL2 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1001\", \"Robinson\", \"Larry\", \"5633 Skyline Drive\", \"Annandale VA\")";

            String SQL3 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1002\", \"Arafat\", \"Yasser\", \"5633 Quidbury Lane\", \"Hezburg Israel\")";

            String SQL4 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1003\", \"Castro\", \"Fidel\", \"5234 Honey Tree Avenue\", \"Port Lunciana Cuba\")";

            String SQL5 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1004\", \"Carter\", \"Jimmy\", \"9234 Mackel Court\", \"Lynchburg VA\")";

            String SQL6 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1005\", \"Boro\", \"Kerebede\", \"2342 Memory Lane\", \"Jamestowne VA\")";

            String SQL7 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1006\", \"Attenborough\", \"David\", \"3330 Peach Lane\", \"Atlanta GA\")";

            String SQL8 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1007\", \"Ahmed\", \"David\", \"30499 Tressleburry Lane\", \"Tampa FL\")";

            String SQL9 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1008\", \"Tramper\", \"Jamie\", \"30499 Dickens Avenue\", \"Dallas TX\")";

            String SQL10 = "INSERT INTO dbo.SELCREATEDB VALUES "
                      + "(\"1009\", \"Valentine\", \"Rudy\", \"8900 Spicetree Lane\", \"San Diego CA\")";


            //SET PROPERTIES
            query.addBatch(SQL);

            //CREATE TABLE
            query.addBatch(SQL_Create);

            //INSERT RECORDS
            query.addBatch(SQL1);
            query.addBatch(SQL2);
            query.addBatch(SQL3);
            query.addBatch(SQL4);
            query.addBatch(SQL5);
            query.addBatch(SQL6);
            query.addBatch(SQL7);
            query.addBatch(SQL8);
            query.addBatch(SQL9);
            query.addBatch(SQL10);

            //EXECUTE ALL COMMANDS
            query.executeBatch();

            //CLOSE CONNECTION
            conn.close();
        }
        catch (SQLServerException sqe)
        {
            System.out.println("A result set was generated for update.");
        }
        catch (java.sql.BatchUpdateException bae)
        {
            System.out.println("Executed Queries! Terminating Connection...");
        }
    }

    @AfterClass
    public void tearDown() throws Exception 
    {
        //Do Nothing
    }
}

我正在使用SQL Server 2012 Standard Edition与AdventureWorks2012数据库建立JDBC连接。任何帮助将非常感激。谢谢!

1 个答案:

答案 0 :(得分:-2)

你拥有的代码绝对没问题,但你为INSERT编写的SQL语句并不是最好的。问题本身就是INSERT个查询!

我已经更正了INSERT查询并执行了一次SQL AUTHENTICATION更改程序并且该程序没有任何问题。

更新的代码:

public class DDLDMLStatementsinJDBC
{
    public static final String URL = "jdbc:sqlserver://localhost:1433;" + "databaseName=Dummy;sendStringParametersAsUnicode=false";
    public static final String DBUSER = "sa";
    public static final String DBPASS = "Welcome12!";

    public static void main(String[] args) throws Exception, SQLException
    {
        try
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  
            Connection conn = DriverManager.getConnection(URL, DBUSER, DBPASS);

            System.out.println("Connection Established ln");
            Statement query = conn.createStatement();


            String SQL = "SET NOCOUNT OFF;";
            String SQL_Create = "CREATE TABLE SELCREATEDB" + "(PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255));";

            String SQL1 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1000, 'Davis', 'John', '3444 Mulberry Lane', 'Oakland CA')";
            String SQL2 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1001, 'Robinson', 'Larry', '5633 Skyline Drive', 'Annandale VA')";
            String SQL3 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1002, 'Arafat', 'Yasser', '5633 Quidbury Lane', 'Hezburg Israel')";
            String SQL4 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1003, 'Castro', 'Fidel', '5234 Honey Tree Avenue', 'Port Lunciana Cuba')";
            String SQL5 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1004, 'Carter', 'Jimmy', '9234 Mackel Court', 'Lynchburg VA')";

            query.addBatch(SQL);
            query.addBatch(SQL_Create);

            query.addBatch(SQL1);
            query.addBatch(SQL2);
            query.addBatch(SQL3);
            query.addBatch(SQL4);
            query.addBatch(SQL5);

            query.executeBatch();

            conn.close();
        }
        catch (SQLServerException sqe)
        {
            System.out.println("A result set was generated for update.");
            sqe.printStackTrace();
        }
        catch (java.sql.BatchUpdateException bae)
        {
            System.out.println("Executed Queries! Terminating Connection...");
            bae.printStackTrace();
        }
    }
}

希望你能得到改变!