JSP connection to Access database code [original]

Source: Internet
Author: User
Tags exception handling getmessage odbc stmt access database import database java web
Code that connects an Access database in a Java Web that you just wrote. These days talking about database operations, but my book is XP Home version, install SQL Server is more cumbersome, simply get access to demonstrate it. Sometimes small desktop databases are pretty practical, huh?

<%@ page contenttype= "text/html; charset=gb18030 "%>
<% @page import= "java.sql.*"%>
<title>
Jsp1
</title>
<body bgcolor= "#ffffff" >
<form method= "POST" action= "/web/index.jsp" >
<%

try{
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e) {
Out.print ("Database driver mount Error");
}

try{
String url= "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D bq=" +request.getrealpath ("/") + "Test.mdb";
Pay special attention to the space between the driver and (*.mdb) above
* * This test.mdb file is stored in the Web module directory, of course, you can change the path.
Connection conn=drivermanager.getconnection (URL);
Statement stmt=conn.createstatement ();
ResultSet rs=stmt.executequery ("SELECT * from Log");//log for table name, same as SQL
while (Rs.next ()) {
Out.print (Rs.getint ("ID") + "&nbsp;&nbsp;");
Out.print (rs.getstring ("username") + "&nbsp;&nbsp;");
Out.print (rs.getstring ("password") + "&nbsp;&nbsp;"); /log three fields in the table, the primary key is the ID, the self increment. Username and password are text types.
Out.println ("<br>");
}
Rs.close ();
Stmt.close ();
Conn.close ();
}

catch (Exception ex) {
Out.print (ex);
}

%>
</form>
</body>

================================================================================
Here are some of the web search JSP or JavaBean connection access code, excerpted from "Http://blog.csdn.net/rimoer/archive/2007/04/06/1554842.aspx"

I wrote a code that connects an Access database with a JSP. To properly use this code, you need to first create a username table in an Access database that creates two-character fields with field names: Uid,pwd, and then inserts a few test data. You are welcome to make suggestions for improvement. The following two ways to implement the JSP connection Access database. The first form of JSP.
Program code <%@ page ContentType = "text/html; charset=gb2312 "language =" java "
import = "java.sql.*"% >
<meta http-equiv = "Content-type" Content = "text/html;" charset=gb2312 ">
<%
/*********************************
JDBC_ODBC connect to an Access database without having to set up a data source
date:2005.8
Email:fanwsp@126.com
Author:dreamtime [Dream Years]
Have any welcome to make corrections
**********************************/


Database Connection Code STARTS * * * *
Exception Handling Statements
Try
{
Please amend the following
Stringspath = "Data/test.mdb"; Access database path
StringDBPath = Application. Getrealpath (spath); into a physical path.
Stringdbname = ""; Acvess database user name, none is null
Stringuser = ""; Access database password, none is empty
Database connection string
Stringurl = "Jdbc:odbc:driver={microsoft Access Driver (*.mdb)};D bq=" +dbpath;
Load Driver
Class. forname ("Sun.jdbc.odbc.JdbcOdbcDriver");
Establish a connection
Connection conn = drivermanager. getconnection (URL);
To create a statement object
Statement stmt =conn. createstatement (ResultSet. Type_scroll_sensitive, ResultSet. concur_updatable);
Database Connection Code Ended

Test data code begins
Create a username table in the database with two field UID and PWD, typed as text
Stringsql = "SELECT * from username";
ResultSet rs = stmt. executequery (SQL);
while(Rs. Next ())
{
Out. Print ("User name:" + Rs. getString ("UID"));
Out. Print ("Password:" + Rs. getString ("pwd") + "<br>");
}
Out. Print ("<br> congratulations." Database connection succeeded. " ) ;
Rs. close (); Close Recordset object
stmt. Close (); Close Statement Object
Conn. close (); Close Connection Object
}catch (Exception e) {
Out. Print ("Database connection error.") , the error message is as follows:<br> ");
Out. Print (E. getMessage ());
}
Test Data code end *******
% >

The second type, the JavaBean form. Program Code/*
***************************************
* Role: Java Connection Access database code
* Author: Dream time
* email:fanwsp@126.com
* Author: Dream time
* CopyRight (c) 2005-2006 by Dreamtime
******** *******************************
*/
[/color]

Package conn; Import Package
import java. sql.                         * ; Classes that import Database operations

PublicClass Dbconnaccess//construction method, initializing
{

PrivateConnection Conn; Connection objects
PrivateStatement stmt; Statement Object
PrivateResultSet rs; Result set Object
Private StringAccessdriver; Save the Access driver string
Private StringAccessurl; Save Access connection string

PublicDbconnaccess ()
{
Access Driver
Accessdriver = "Sun.jdbc.odbc.JdbcOdbcDriver";
Connection string
Accessurl = "Jdbc:odbc:driver={microsoft Access Driver (*.mdb)};D bq=";
conn = NULL;
}

This method obtains the database path from the parameter, adds it to the connection string, and then establishes the connection
PublicConnection getconntoaccess ( StringDBPath) {
try {
Accessurl =accessurl +dbpath;
Class. forname (Accessdriver);
conn = DriverManager. getconnection (Accessurl);
}catch (Exception e) {
System. Out. println ("Operation database error, please check carefully");
System. Err. println (E. getMessage ());
}
returnconn;
}



To close a database connection
Publicvoid Close ()
{
try {
Rs.close ();
Stmt.close ();
Conn. close ();
}catch (SQLException SQLException) {
SqlException. Printstacktrace ();
}
}
}

The calling method is as follows: program code <meta HTTP-EQUIV = "Content-type" Content = "text/html; charset=gb2312 ">
<%@ page ContentType = "text/html; charset=gb2312 "language =" java "
import = "java.sql.*"% >
<jsp:usebean id = "Dbconn" scope = "page" class = "conn." Dbconnaccess "/>
<%
Connect to an Access database
StringDBPath = "Data/test.mdb"; The path to the database, please modify it yourself
Connection Conn =dbconn getconntoaccess (application. Getrealpath);
Statement stmt =conn. createstatement (ResultSet. Type_scroll_insensitive, ResultSet. CONCUR_READ_ONLY);
Stringsql = "SELECT * from username order by id";
String sql1= "INSERT into username (uid,pwd) VALUES (' wsp ', ' wsp ')";
Stmt.executeupdate (SQL1);
ResultSet rs =stmt. executequery (SQL);

while(Rs. Next ()) {
Out. Print ("User name:");
   &n
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.