Java Database Connectivity - Basics 2
JDBC is an API that allows access to databases from clients using the Java language.
This post will discuss:
- Example Queries
- PreparedStatement Object
Example Queries
Queries can be initialized to variables to receive their return values or can be executed standalone with the methods:
Executes a DDL statement (CREATE, USE) with bool return:
bool rSetPossible = statement.execute(QUERY);
Executes DML statements (INSERT, UPDATE, DELETE) with int return specifying the number of manipulated rows:
int row = statement.executeUpdate(QUERY);
Executes statements that return data (SELECT) with return to a ResultSet:
ResultSet rS= statement.executeQuery(QUERY);
String form (for reference):
DELETE
String ins = "DELETE FROM userinfo WHERE user_id='"+userId+"'";
stmt.executeUpdate(ins);
INSERT
String ins = "INSERT INTO userinfo VALUES ('"+userId+"','"+userPw+"','"+userName+"','"+userEmail+"')";
stmt.executeUpdate(ins);
UPDATE
String ins = "UPDATE userinfo SET user_id='"+userId+"', user_pw='"+userPw+"', user_name='"+userName+"', email='"+userEmail+"' WHERE user_id='"+originalUserId+"'";
stmt.executeUpdate(ins);
PreparedStatement Object
SQL statements can be precompiled. .setObject methods can be used to set values for parameters marked with ? that are indexed from n=1. The type of specified object determines the datatype of the inserted value.
Query has syntax:
STATEMENT FROM table WHERE attribute = ?
Java syntax:
PreparedStatement pS = con.prepareStatement(QUERY);
//set value for attributes
pS.setString(1, value);
//execute
pS.execute();
-gonkgonk