Sample JDBC connection to sqlserver database

  • 2020-04-01 03:20:32
  • OfStack

1. Process:

1 > Registered drive Class: class.forname ()

2 > Connect to database:


String url = "jdbc:sqlserver://localhost:1433;DatabaseName=DataBaseName";
String uername = "dbuser";
String password = "secret";
Connection conn = DriverManager.getConnection(url,username,password);

3 > Execute the SQL statement:

The Statement stat = conn. CreateStatement ();
String command = "UPDATE BOOKS";
Stat. ExecuteUpdate (command);
[/ code]

2. Java.sql.Statement()(three execution methods)

The first: execute(); Void can execute any SQL statement

The second: executeUpdate(); int

You can perform: INSERT UPDATE DELETE
The CREATE TABLE; DROP TABLE

Returns: number of affected rows
The third: executeQuery(); The ResultSet
Implementation: SELECT
Returns: a ResultSet object, iterating one row at a time
Ex. :


ResultSet rs = stat.executeQuery("SELECT * FORM BOOKS") ; 
while(rs.next()){
look at a row of the result set
}
rs.getString(1); Returns the value of the first column of the current row 
rs.getDouble("Price");


GetResultSet (); The ResultSet
Returns the result set; If it is empty, it is null
GetUpdateCount (); Int returns the number of affected rows or -1 if not updated
Close (); Void closes the Statement object and its corresponding result set
IsClose (); Boolean is true if the statement is closed

3. Java. SQL.ResultSet(ResultSet operation method)

The next (); Boolean moves forward one line to the last line and returns false
GetXxx (int columnNum); Xxx
GetXxx (String columnNum); XxxXxx means int double String Date
FindColumn (String columnName); Int gives the column name and returns the column number
Close (); Void closes the current result set
IsClose (); Boolean is true if the statement is closed

4. The principle:

1 > One or more Statement objects can be created per Connection object
The same Statement object can be used for multiple unrelated commands and queries, but only one result set can be opened

2 > The close method should be called immediately after use

3 > If the Statement object has an open result set, the result set is automatically closed by calling close().
The Connection class closes all statements on the Connection


Related articles: