Home Database Mysql Tutorial Java 链接access数据库的方法

Java 链接access数据库的方法

Jun 07, 2016 pm 03:43 PM
access java database method Want to use Link

最近需要用java做一个小功能,需要链接access 数据库 ,在网上找了好多, 方法 都差不多,现总结下,供大家参考。 我的office版本是2010的,所以access 数据库 文件的后缀是.accdb,在发布系统的时候, 数据库 文件放在项目中跟tomcat一起发布,这样方便部署

  最近需要用java做一个小功能,需要链接access数据库,在网上找了好多,方法都差不多,现总结下,供大家参考。

  我的office版本是2010的,所以access数据库文件的后缀是.accdb,在发布系统的时候,数据库文件放在项目中跟tomcat一起发布,这样方便部署。

  1、获取数据库路径:

    <span>//</span><span> 获取<strong>数据库</strong>文件路径</span><span><br></span>    <span>public</span> <span>static</span> String getPath(){<br>        String path = "";<br>        String projectName="Test";<br>        path = System.getProperty("user.dir");    <span>//</span><span> 获取到tomcat的bin目录地址</span><span><br></span>         path = path.replace("bin", "webapps")+"\\"+projectName+"\\Data\\test.accdb";<br>       <span>return</span> path;<br>        <br>    }
Copy after login

  2、建立数据库连接:

  url中,*.mdb, *.accdb 这两个之间要有空格,否则会报错误:java.sql.SQLException: [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序;

  PWD是数据库密码,如果没有的话可以不用写。

    <span>//</span><span> 建立<strong>数据库</strong>链接</span><span><br></span>    <span>public</span> <span>static</span> Connection getConnection() <span>throws</span> SQLException, ClassNotFoundException{
Copy after login
     String path = getPath();<br>        String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+path+" ;PWD=123456789";<br>        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");<br>        Connection conn = DriverManager.getConnection(url);<br>        <span>return</span> conn;<br>        <br>    }
Copy after login

  3、简单查询数据:

    <span>//</span><span> 根据SQL语句,返回查询结果的第一行第一列</span><span><br></span>    <span>public</span> <span>static</span> String getScalar(String strSQL) {<br>        String rValue = "";<br>        Connection conn = <span>null</span>;<br>        <span>try</span> {<br>            conn = getConnection();<br>            Statement st = conn.createStatement();<br>            <span>//</span><span>System.out.println(strSQL);</span><span><br></span>            ResultSet rs = st.executeQuery(strSQL);<br>            <span>if</span> (rs.next()) {<br>                rValue = rs.getString(1);<br>                <br>            } <br>            rs.close();<br>            st.close();<br>            conn.close();<br>            <br>        } <span>catch</span> (Exception e) {<br>            System.out.println("<strong>数据库</strong>连接发生错误,错误信息:" + e.toString());<br>        } <span>finally</span> {<br>            <span>try</span> {<br>                <span>if</span> (conn != <span>null</span> && !conn.isClosed())<br>                    conn.close();<br>            } <span>catch</span> (SQLException ex1) {<br>                System.out.println("<strong>数据库</strong>关闭发生错误,错误信息:" + ex1.toString());<br>            }<br>        }<br>        <span>return</span> rValue;<br>    }
Copy after login


  就先写到这里了,第一次写博客,有写的不好的地方或者代码不合适的地方欢迎大家指点。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

MySQL: Structured Data and Relational Databases MySQL: Structured Data and Relational Databases Apr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities Explained MySQL: Key Features and Capabilities Explained Apr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

Title: Use Composer to solve the problem of unified representation of complex data types Title: Use Composer to solve the problem of unified representation of complex data types Apr 18, 2025 am 08:33 AM

Summary Description: When dealing with complex data types, you often encounter problems of how to uniformly represent and operate. This problem can be easily solved with Composer using the phrity/o library. It provides encapsulation classes and traits for various data types, making data processing more consistent and efficient.

Solve memory management problems in Magento project: application of zend-memory library Solve memory management problems in Magento project: application of zend-memory library Apr 17, 2025 pm 11:03 PM

I'm having a tough memory management problem while working on a Magento project. As the project involves a large amount of data processing, memory consumption increases rapidly, resulting in system performance degradation and even crashes. After some research, I discovered the zend-memory library, which effectively solved my memory management problem.

What are the plugins for wordpress blocking ip What are the plugins for wordpress blocking ip Apr 20, 2025 am 08:27 AM

WordPress IP blocking plugin selection is crucial. The following types can be considered: based on .htaccess: efficient, but complex operation; database operation: flexible, but low efficiency; firewall: high security performance, but complex configuration; self-written: highest control, but requires more technical level.

See all articles