简体   繁体   中英

How do I CREATE a table and INSERT records into table using JDBC?

I am attempting to execute multiple SQL statements at once using JDBC. I am aware that the addBatch() and executeBatch() functions can be used to accomplish this. I have incorporated them into my code and even "SET NOCOUNT OFF" but my CREATE and INSERT statements were not reflected in my SQL Server database. Here is what I have attempted below:

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
    }
}

I am using SQL Server 2012 Standard Edition with an Established JDBC Connection to the AdventureWorks2012 database. Any help would be much appreciated. Thank You!

The code that you have is absolutely fine but the SQL statements that you've written for your INSERT's are not one of the finest. The issue was the INSERT queries in itself!

I've corrected the INSERT queries and executed the program with one change, of SQL AUTHENTICATION and the program worked with no issues.

Updated code:

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();
        }
    }
}

Hope you are able to get the change!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM