Java implementation connection SQL Server 2000 (JDBC Database Access Example)

xiaoxiao2021-03-06  15

Liu Jinlong 04041222 ljlsunny@vip.sina.com

The first: connected to the database via the ODBC

The Java language cross-platform work ability (Write Once, Run Anywhere), excellent image processing capabilities (I believe that there is no language that can exceed Java's graphics processing power on the network), network communication function, access technology through JDBC database Wait, let us see the Java language is a huge contribution to the computer world. The author can describe such a scenario: One day, you can use IE or Netscape, you can get the game, you can get the game, the feeling of the game, if you have played UO, maybe you know that I feel, but the things made by Java will definitely exceed UO, because not only the game, not only a browser, if you are willing (want you have money, there is a good Java talent) You can put all All this is integrated with Java! ! ! I am not exaggerating Java's function. You can visit http://www.simchina.net, you can find a feeling: I believe I don't say something. Ok, don't say nonsense, now I introduce you to Java database access technology ---- JDBC database access technology (you must don't get ODBC!). JDBC technology is actually an application interface (API) that can access any structured database through the Java language (SUN says, I don't know if it is true), and now the JDBC 3.0 according to Sun said it can also be accessed. Execel and other spreadsheets! JDBC has four ways to access the database, we just introduce two: The first is to access database database through ODBC, and the second is to access databases. Let's take a look at the first JDBC <-> ODBC access process: jdbc driver mannager-> jdbc <-> odbc bridge -> odbc-> database client drive -> database server -> return query results, We pay attention to this type of visit to the name of "Write Once, Run Anywhere", but if you pass this kind of access, you need to set the ODBC and drive drive with the corresponding database client, when you look below At another process, you will think: clearly, why do you have to produce this thing! Oh, because all database server providers are not available to provide the following JDBC drivers (to provide the JDBC Access to provide the corresponding interface), so there is JDBC <-> ODBC Bridge. Let us then take a look at the second access process: JDBC Driver Mannager-> Local JDBC Drive -> Client Database -> Database Server -> Return Query Results, this access is actually a database of conversion JDBC to the corresponding database ( Oracle, Sybase, Informix, DB2, and other database database management systems) client API calls (so, don't know if you can understand, saying that simple point is as if ASP is not accessible through DSN but through OLEDB access, Said here, I still don't know if you can understand what I mean. Oops, don't throw eggs!), This way access requires the corresponding database provider to provide the corresponding JDBC driver, but there is a benefit, can be independent of ODBC Applet programs used in a browser that can RUN-only clients.

Let's give you an instance accessible through the JDBC-ODBC bridge database, but I would like to ask everyone before looking at the following example: JDK1.3 is installed? Is the database driver (I use SQLServer)? Do you have any Linux? Although Java supports Linux, but I can use Linux 哟 (this is nothing to do with Java's Write Once, Run Anywhere), because I use ODBC below Win, I suggest you see this thing http: // www .aspcn.com / showArticle.asp? id = 112, otherwise you have a problem, you can't do anything, isn't that you want to blame me (but you want to add the sin, why not eat ...), 冤! Oops, I said so many nonsense, let us see the JDBC call! Since we pass the ODBC to access the database, this ODBC can't run, let's set your ODBC: Open your ODBC Data Source -> Select System DSN (Click Add DSN -) -> Next Enter Select Database Type, enter the DSN name:, select the server, connect the database, enter the login user and password of the database -> Test connection, if the test is successful, then your DSN is established, my DSN is named SQL Server. Used Is SQLServer7.0, login with "sa", password is empty.

These things have to be used later! Ok, let's look at the program code: (This code has been running) // ############################# ################################################################################################################################ ###############################; s; // Load the Java data connection package, the call of the Java basic database is in this thing PUBLIC Class InsertCoffees {public static void main (string args []) {string url = "jdbc: ODBC: SQLSERVER"; // Connected URL name, note SQLServer is a DSN name connection con; // instantiate a connection object statement stmt; string query = "select * from col_link"; // Select the data output in all col_link tables Try {class.Forname "sun.jdbc.odbc.jdbcodbcdriver"); // load JDBC-ODBC bridge driver} catch (java.lang.classnotfoundexception e) {system.err.print ("ClassNotFoundExce:"); // Load JDBC-ODBC Bridge error System.err.Println (E.GetMessage ()); // Other Error} try {con = drivermanager.getConnection (URL, "SA", ""); // Database connection STMT = con.createstatement (); // Create Stimt.executeUpdate ("Create Table Col_Link (SiteURL VARCHAR (20) NULL, SiteURL VARCHAR (50) NULL"); // Execute a SQL statement to generate a table col_link table stmt.executeUpdate ("Insert Into Col_Link Values ​​('ASP China Network ",' http: // www. Aspcn.com ') "); stmt.executeUpdate (" INSERT INTO COL_LINK VALUES ("How far is much forever",' http://xuankong.com ') ")") "); // Perform an Insert INTO statement Stmt.executeUpdate "Update col_link set siteURL = 'http://www.aspcn.com/xuankong/xuankongt.jpg' where siteURL = 'http://xuankong.com'"); // Perform a Update statement, update the database ResultSet RS = Stmt.executeQuery (query); // Returns a result set System.out.Println ("The data in the col_link table is as follows (raw data)"); // The following statement uses a While loop print out in the col_link table All data system.out.println ("Site Address" "Site Address"); System.out.Println ("-------------"

" " ---------------- "); while (rs.next ()) {string s = rs.getstring (" sitename "); string f = rs. GetString ("SiteURL"); // Get the data in the database system.out.println (s "" f); / * string t = rs.getstring (1); string l = rs.getstring (2); System.out.println (t " l); * / / * JDBC provides two way to identify fields, one is to use GetXXX (note that getxxx here) get field names for different methods of different types of fields) The second product is indexed by field, here I annotate the second method * / / * You can access this connection to get getxxx usage: http://java.sun.com/docs/books/Tutorial/ JDBC / BASICS / _RETRIEVINGTABLE.HTML * /} stmt.close (); con.close (); // The above statement closing declaration and connection} catch (sqlexception ex) {system.err.println ("SQLException:" EX .getMessage ()); // Display database connection error or query error}}} // ############################# ################################################################################################################################################################################################################################################################################################# ###################################### I want you to show how to use the JDBC-ODBC to connect to the database. Use the SQL statement to generate a table, using the SELECT, INSERT, UPDATE sentences, insert and update the data in a table, how to access the Database through the field name and field index ! I hope that you can really learn something from the code! Play your imagination, try to do Java, for example, you can make a chat room without the GUI (graphical user interface) through the database, huh, feel like the chat room in the DOS environment! Haha! Finally, it is necessary to say the author's debugging the environment: Win2000, JDK1.3, MS SQLServer Editing Software: Editplus 2.01A (this is not nonsense, although there are some professional Java development tools, but the author suggest Java beginners use text software to develop Java programs) Second: directly access database with JDBC

(1) This example has been run

JSP connection SQL Server7.0 / 2000 database testsqlserver.jsp is as follows: <% @ page contenttype = "text / html; charSet = GB2312"%> <% @ page import = "java.sql. *"%> < Body> <% class.Forname ("com.microsoft.jdbc.sqlser.sqlserdriver). NewInstance (); string url =" JDBC: Microsoft: SQLServer: // localhost: 1433; databasename = pubs; // Pubs String user of your database = "sa"; String password = ""; Connection conn = DriverManager.getConnection (url, user, password); Statement stmt = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql = "Select * from test"; ResultSet RS = stmt.executeQuery (SQL); while (rs.next ()) {%> Your first field content is: <% = rs.getstring (1);%> you The second field content is: <% = rs.getstring (2);%> <%}%> <% out.print ("Database operation is successful, congratulations");%> <% rs.close () Stmt.close (); conn.close ();%> (2) Java Access SQLServer server

Step 1: Install JDBC

Click SQL Server for JDBC Driver Setup Setup.exe (you can go to Microsoft website to download http://msdn.microsoft.com/library/default.asp?rul=/downloads/list/sqlserver.asp Download)

Step 2: Set system variables ClassPath

Assuming the SQL Server for JDBC driver is installed in D: / JDBC /, the classpath should be set as follows:

Classpath: = .; ...; D: / JDBC / LIB; D: /JDBC/LIB/Mssql Server.jar; D: /jdbc/lib/msutil.jar; D: /JDBC/LIB/msbase.jar;

Note: When set, you want to be in front of the point and semicolon

Step 3: Edit the Java program and run

Example 1 is as follows:

// Import com.microsoft. *;

// Note: Do not need this package when Java and SQL Server is connected, other books say this package is required, this problem needs further discussion

Import java.sql. *;

Import java.net.URL;

Class Insert

{

Public static void main (string [] args)

{

String URL = "JDBC: Microsoft: SQLServer: // localhost: 1433; databasename = northwind"; string query = "select * from categories";

String query1 = "INSERT CATGORIES VALUES (10, 'Hanbao', 'Sweet')"

String query2 = "Insert Categories VALUES (11, 'Naicha', 'Coffee Taste')

Try

{

Class.Forname ("com.microsoft.jdbc.sqlser.sqlserverdriver);

Connection Con = DriverManager.getConnection (URL, "SA", "739555");

Statement Stmt = con.createstatement ();

Stmt.executeUpdate (query1);

Stmt.executeUpdate (query2);

Stmt.close ();

C. close ();

}

Catch (SQLException EX)

{

}

Catch (java.lang.exception ex)

{

EX.PrintStackTrace ();

}

}

}

Example 2 is as follows:

// Import com.microsoft. *;

// Note: Do not need this package when Java and SQL Server is connected, other books say this package is required, this problem needs further discussion

Import java.sql. *;

Import java.net.URL;

Class Java2Sql Server

{

Public static void main (string [] args)

{

String URL = "JDBC: Microsoft: SQLServer: // localhost: 1433; user = sa; password = 739555; databasename = northwind

String query = "select * from categories";

Try

{

Class.Forname ("com.microsoft.jdbc.sqlser.sqlserverdriver);

//Drivermanager.setlogstream(stem.out);

Connection con = DriverManager.getConnection (URL);

Checkforwarning (con.getwarnings ());

Statement Stmt = con.createstatement ();

ResultSet RS = Stmt.executeQuery (Query);

DispResultSet (RS);

Rs.close ();

Stmt.close ();

C. close ();

}

Catch (SQLException EX)

{

System.out.println (ex. Tostring () "---- SQLEXCEPTION CAUGHT ----");

While (ex! = null)

{

System.out.print ("SqlState:" ex.getsqlstate ());

System.out.print ("Message:" ex.getMessage ()); system.out.print ("vendor:" ex.GetersRrorcode ());

EX = ex.getnextexception ();

System.out.println ("");

}

}

Catch (java.lang.exception ex)

{

EX.PrintStackTrace ();

}

}

Private Static Boolean CheckforWarning (Sqlwarning Warn)

{

Boolean rc = false;

IF (Warn! = NULL)

{

System.out.println ("---- Warning ----");

Rc = true;

While (Warn! = null)

{

System.out.print ("SqlState:" Warn.getsqlState ());

System.out.print ("Message:" warn.getMessage ());

System.out.print ("vendor:" warn.geterrorcode ());

System.out.println ("");

Warn = warn.getnextwarning ();

}

}

Return RC;

}

Private Static Void DispResultset (ResultSet RS) THROWS SQLEXCEPTION

{

INT I;

ResultSetmetaData RSMD = rs.getMetadata ();

INT Numcols = rsmd.getColumnCount ();

For (i = 1; i <= numcols; i )

{

IF (i> 1) system.out.print (",");

System.out.print (RSMD.GetColumnLabel (i));

}

System.out.println ("");

Boolean more = rs.next ();

WHILE (more)

{

For (i = 1; i

{

IF (i <1) system.out.print (",");

System.out.println (Rs.getstring (i));

}

System.out.println ("");

More = rs.next ();

}

}

//System.out.println ("Hello World!");

}

The above two instance writers have been run!

转载请注明原文地址:https://www.9cbs.com/read-47481.html

New Post(0)