JDBC

farrightΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 4 χρόνια και 8 μήνες)

316 εμφανίσεις

JDBC

JDBC


JDBC (Java Database Connectivity):


JDBC

is an API for the Java programming
language that defines how a client may
access a database. It provides methods for
querying and updating data in a database.

How to connect Java to SQL
Server?

Step
1


Extract the JDBC in the C:
\

Driver

Step
2


Copy the file
sqljdbc.jar

from
C:
\
Microsoft SQL
Server
2005
JDBC Driver
\
sqljdbc_
1.0
\
enu

to
C:
\
Program
Files
\
Java
\
jdk
1.6.0
_
20
\
jre
\
lib
\
ext



Copy the file
sqljdbc_xa.dll

from
C:
\
Microsoft SQL
Server
2005
JDBC Driver
\
sqljdbc_
1.0
\
enu
\
xa
\
x
86

to
C:
\
Program Files
\
Java
\
jdk
1.6.0
_
20
\
jre
\
lib
\
ext


Step
3
: Configuring NetBeans


Add the JDBC jar library to NetBeans
Environment:


Click the tools menu choose the Java platforms then
choose the source tab and add the JDBC jar library.



Or you can add it to one of your application:


Right click on the application and choose the
properties and then choose libraries then add the
JDBC jar library.

Step
4
: Configuring SQL sever


Click start >> Microsoft Sql server >>
Configuration tools >> Sql server
configuration manager.


Step
4
(continued)

Step
4
(continued)

Step
4
(continued)

Connection to Database


Connect to sql server.


Class.forName("com.microsoft.sqlserver.jdbc.SQLServer
Driver");



Connect to the database


DriverManager.getConnection
("jdbc:sqlserver://localhost
\
\
SQLEXPRESS;
database=master; user= sa; password=
123456
");

Connect to the
database server

Database
instance
name

Database name

User name
to connect to

Password for
user sa

DML using Java


public void dml(String x)


{


try


{


stmt.executeUpdate(x);



}


catch(SQLException sqle)


{


System.err.println(sqle);


}


}

To execute
insert, update,
delete statement

Instance of the Statement

(To execute any sql statement)

Select using Java


public ResultSet select(String x)

{


try


{



ResultSet r=stmt.executeQuery(x);



return r;


}


catch(SQLException sqle)


{



System.err.println(sqle);



return null;


}

}

To execute
select
statement
using Java

To retrieve the result of the select
statement

Methods to retrieve rows


r.next():

to let the
cursor points to next
row.



r.getString(index)


r.getString(column
name):



to retrieve a column
using index or
column name