Home > Enterprise >  Connection with SQL IF condition Errors
Connection with SQL IF condition Errors

Time:12-29

I am trying to connect my java project to the database. I am creating a method to create a table using this code

package DataBaseConnectivity;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

public class DataBaseConnectivity {
    public static void main(String args[]) {

        // Creating the connection using Oracle DB
        // Note: url syntax is standard, so do grasp
        String url = "jdbc:sqlserver://localhost:1433;databaseName=SchoolMgt;encrypt=true;trustServerCertificate=true";

        // Username and password to access DB
        // Custom initialization
        String user = "sa";
        String pass = "root";

        // Entering the data

        Scanner scanner = new Scanner(System.in);

        String tableCreationsql = " create table  Students ( id integer PRIMARY KEY,fname VARCHAR (8),birthdate date,lname VARCHAR (8))";

        Connection con = null;

        // Try block to check for exceptions
        try {

            Driver driver = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            // Registering drivers
            DriverManager.registerDriver(driver);

            // Reference to connection interface
            con = DriverManager.getConnection(url, user, pass);

            // Creating a statement
            Statement st = con.createStatement();

            // Executing query
            int Executing = st.executeUpdate(tableCreationsql);
            if (Executing >= 1) {
                System.out.println("Created Successfully : "   tableCreationsql);
            } else {
                System.out.println("Creation Is Failed");
            }
            // Closing the connections
            con.close();
        }

        // Catch block to handle exceptions
        catch (Exception ex) {
            // Display message when exceptions occurs
            System.err.println(ex);
        }
    }

}

The code works fine but it never enters the if condition it directly move to the else Also the table is some how is created even though it goes to else

I am expecting to get Creation is successful and table shall be created in database.

CodePudding user response:

executeUpdate returns the number of rows affected (see the documentation)

Since you are creating a table (DDL statement) 0 rows are affected, hence Executing equals 0

  • Related