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

Skrócony zapis if - instrukcja warunkowa java

Instrukcja warunkowa - warunek i rezultat. if (warunek) { jesli spełniony wykonań operacje i zwróć wynik; } warunek nie spełniony Możliwości skrócenia kodu instrukcji warunkowej if (i < 0) ? i-- : i++; Jeżeli i mniejsze od zera to i-- jezeli false to i++ if (i < 0) {     i--; } else {     i++; } Skrócony zapis instrukcji warunkowej else if (i < 0) ? i--;  inna_zmienna=4; : i++; if (i < 0) {     i--; } else {     i++;     inna_zmienna = 4; } Skrócony zapis if

wait and notify() Methods in Java - rekrutacja

Synchronizacja wątków. Procesor może wykonywać wiele zadań jednoczenśnie - concurrent software. Java wspiera współbieżność jest potrzebna synchronizacja ponieważ różne wątki threads mogą w tym samym czasie usiłować zmodyfikować ten sam zasób jeśli nie są zarządzane poprawinie. Object.wait() - zawiesza wątek - thread suspension Object.notify() - wznów wątek - thread wake up Object.notifyAll() - wznowienie wszystkich wątków

Runnable and Call able - Java rekrutacja

Runnable - interfejs zawierający metode run() - obiekt implementujący tą metodę tworzy wątek thread public interface Runnable The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run. This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.  In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclas...