Przejdź do głównej zawartości

Inserting Data into SQL Database with Java

Inserting Data into SQL Database with Java




Java Documentation - Processing SQL statements with JDBC 

Process:

  1. Get connection to database
  2. Create a statement
  3. Execute SQL query


import java.sql.*;

/**
 *
 * @author www.luv2code.com
 *
 */
public class JdbcTest {

public static void main(String[] args) throws SQLException {

Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;

String dbUrl = "jdbc:mysql://localhost:3306/demo?autoReconnect=true&useSSL=false";
String user = "root";
String pass = "Sasanka01";

try {
// 1. Get a connection to database
myConn = DriverManager.getConnection(dbUrl, user, pass);
System.out.println("Database connection successfully created");

// 2. Create a statement
myStmt = myConn.createStatement();

int rowsAffected = myStmt.executeUpdate(
                         "insert into employees " +
                         "(last_name, first_name, email, department, salary)"+
                         "values" +
                          "('Wright', 'Eric', 'eric.wright@foo.com', 'HR',33000.00)");

//System.out.println(rowsAffected);

// 3. Execute SQL query
myRs = myStmt.executeQuery("select * from employees");

// 4. Process the result set
while (myRs.next()) {
System.out.println(myRs.getString("last_name") + ", " + myRs.getString("first_name"));
}
}
catch (Exception exc) {
exc.printStackTrace();
}
finally {
if (myRs != null) {
myRs.close();
}

if (myStmt != null) {
myStmt.close();
}

if (myConn != null) {
myConn.close();
}
}
}

}

-------------------------


Creating Statements
A Statement is an interface that represents a SQL statement. You execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. You need a Connection object to create a Statement object.

For example, CoffeesTables.viewTable creates a Statement object with the following code:
stmt = con.createStatement();


There are three different kinds of statements:
  1. Statement: Used to implement simple SQL statements with no parameters.
  2. PreparedStatement: (Extends Statement.) Used for precompiling SQL statements that might contain input parameters. See Using Prepared Statementsfor more information.
  3. CallableStatement: (Extends PreparedStatement.) Used to execute stored procedures that may contain both input and output parameters. See Stored Procedures for more information.
Executing Queries
To execute a query, call an execute method from Statement such as the following:
  1. execute: Returns true if the first object that the query returns is a ResultSet object. Use this method if the query could return one or more ResultSet objects. Retrieve the ResultSet objects returned from the query by repeatedly calling Statement.getResultSet.
  2. executeQuery: Returns one ResultSet object.
  3. executeUpdate: Returns an integer representing the number of rows affected by the SQL statement. Use this method if you are using INSERT, DELETE, or UPDATE SQL statements.

For example, CoffeesTables.viewTable executed a Statement object with the following code:
ResultSet rs = stmt.executeQuery(query);

-------------------

INSERT query
int rowsAffected = myStmt.executeUpdate(
                         "insert into employees " +
                         "(last_name, first_name, email, department, salary)"+
                         "values" +
                          "('Wright', 'Eric', 'eric.wright@foo.com', 'HR',33000.00)");
DELETE query

int rowsAffected = myStmt.executeUpdate(
"delete from employees " + 
"where last_name='Wright' and first_name= 'Eric'");

System.out.println(rowsAffected);

Komentarze

Popularne posty z tego bloga

SQL - Podstawy

SELECT * FROM branch; CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, .... ); Typy danych w kolumnach Text data types: VARCHAR (40) - string z ograniczoną liczbą znaków TEXT - string BLOB - Binary Larg Objects - 65000 bytes of data ENUM('X','Y','Z') - list of values in order we enter them SET - values are ENUM up to 64 list items    Number data types: INT (size) - integer FLOAT(size,d) - small number with floating decimal point, d - decimal point DOUBLE(size,d) large number with floating decimal point Date data types: DATE() - YYYY-MM-DD TIMESTAMP() TIME() SQL Keywords: ADD - add column ALTER - add delete modify columns in table or change data types of column in table CREATE - create database, table, index, view, procedure CREATE DATABASE CREATE TABLE CREATE INDEX CREATE VIES DELETE - delete rows from table DESC - sort results descending order DROP - delet...

Java -Arrays

Array - data structure that allows us to store multiple values of the same type into a single variable Default value - zero Arrays are zero indexed - Array with ten elements will be indexed from 0 to 9 Array[] How to create array: int[] array = new int[5]; (boxes have value zero - secured slot in memory to hold values) int[] myArray = {1,2,3,4,5}; this type of initializing an array is also known as an anonymous array boolean type arrays - default value is false Errors while working with arrays ArrayIndexOutOfBoundsExeption int[] my Array = {10,35,45,78,55} myArray[5] = 55; out of bound index 5 does not exist int[] myArray = {10,15,20,17,18}; for (int i=1 ; i < myArray.lenght; i++)  System.out.println("value= " + myArray[i] it will return values from index 1 How to print out simple int array? example: int [] myArray = new int [ 2 ] ; myArray[ 0 ]= 0 ; myArray[ 1 ]= 1 ; System. out .println( "My array: " + ...

Stored Procedures - JDBC Java SQL

Stored Procedures: group of SQL statements that perform a particular task  Normally created by DBA Can have any combination of input, output, and input/output parameters Benefits: Performance  - compiled once but executable more times Productivity and Ease of Use  - avoid redundant code, extend SQL Database functionality  Scalability   Maintainability Interoperability Replication Security To call stored procedure from Java The JDBC API provides the CallableStatement CallableStatement myCall = myConn.prepareCall("{ call some_stored_procedure() }"); ... myCall.execute(); JDBC API parameter types IN default INOUT OUT Stored Procedure can return result sets EXAMPLE: Created stored procedure on MySQL side - NAME:  increase_salaries_for_department DELIMITER $$ DROP PROCEDURE IF EXISTS ` increase_salaries_for_department `$$ CREATE DEFINER=`student`@`localhost` PROCEDURE `increase_salaries_for_departme...