search
HomeDatabaseMysql TutorialJava 实现连接sql server 2000

JDBC技术事实上是一种能通过JAVA语言访问任何结构化数据库的应用程序接口(API)(Sun这样说的,我也不知道是不是真的),而且现在的JDBC 3.0据Sun说也能访问Execel等电子表格程序!

第一种:通过ODBC连接数据库

JAVA语言的跨平台的工作能力(Write Once ,Run Anywhere)、优秀的图像处理能力(我相信现在没有那种语言可以超过JAVA在网络上的图形处理能力)、网络通信功能、通过JDBC数据库访问技术等等,让我们谁都不可否认JAVA语言是SUN公司对于计算机界的一个巨大的贡献。笔者可以描述这样一个场景:有一天你上网完全可以不用IE 或者NETSCAPE,上网就像是玩游戏,你可以获得游戏那么精美的图像和互动的感觉,如果你玩过UO,也许你就知道那种感觉了,但是JAVA做成的东西一定会超过UO的,因为不单单是游戏,也不是单单是浏览器,如果你愿意(要你有钱,有时间,有优秀的JAVA人才)你可以把所有的这一切用Java完全集成出来!!!我不是夸大JAVA的功能,大家可以访问一下http://www.simchina.net的那个社区程序,你就能找到一种感觉了:相信我没有说什么假话 。好了,不说废话了,现在我向你介绍JAVA的数据库访问技术----JDBC数据库访问技术(你可千万不要搞成ODBC了!)。
  JDBC技术事实上是一种能通过JAVA语言访问任何结构化数据库的应用程序接口(API)(Sun这样说的,我也不知道是不是真的),而且现在的JDBC 3.0据Sun说也能访问Execel等电子表格程序!
  JDBC对于数据库的访问有四种方式,我们这里只是介绍两种:
  第一种是通过ODBC做为“桥”(Bridge)对数据库访问,第二种是直接对数据库访问。
  我们先来看看第一种JDBCODBC访问的流程:
  JDBC Driver Mannager->JDBCODBC桥->ODBC->数据库客户机驱动库->数据库服务器->返回查询结果,在这种访问中值的我们注意的是虽然JAVA是"Write Once ,Run Anywhere",但是如果通过这种访问的话,需要客户端必须设置ODBC和有相应的数据库客户机的驱动,当你看了下面的另外一个流程的时候或许你会想:明明下一种更方面,为什么还要有这个东西的产生!呵呵,因为,未必所有的数据库服务器提供商都提供下面的JDBC驱动程序(给JDBC访问提供相应的接口),所以就有了JDBCODBC Bridge。
  接着再让我们来看看第二种访问流程:
  JDBC Driver Mannager->局部JDBC驱动->客户端数据库->数据库服务器->返回查询结果,这种访问事实上是转换JDBC调用为相应的数据库(Oracle, Sybase, Informix, DB2, 和其他的数据库数据库管理系统)的客户端API调用(这么说,不知道大家能不能懂,说简单点就好像ASP不是通过DSN对数据库访问而是通过OLEDB访问,说道这里我还是不知道大家能不能明白我的意思。哎呀,不要扔鸡蛋嘛!),这种方式的访问需要相应的数据库提供商提供相应的JDBC驱动程序,但是有一种好处,可以独立于odbc用于可以随处可Run的客户端的浏览器中的Applet程序。
我们下面将给大家一个通过JDBC-ODBC桥数据库访问的实例,但是在看下面的事例前我想问大家一次:JDK1.3装了吗?数据库驱动装了吗(我使用的是SQLserver)?你该没有使用Linux吧?虽然java支持Linux,但是老兄我可没有使用Linux哟(这同JAVA的Write Once ,Run Anywhere没有关系),由于使用了运行于Win下面的ODBC,我建议你看看这篇东西http://www.aspcn.com/showarticle.asp?id=112,否则你要是有了问题,出不了结果那岂不是要怪我(不过欲加之罪,何患无吃... ...),冤枉呀!

哎呀,说了这么多的废话,还是让我们来看看到底JDBC的调用吧!既然我们是通过odbc访问数据库,所以这个odbc是跑不了的,我们先来设置你的odbc:打开你的odbc数据源->选择系统dsn(Click加新的dsn-)->接下来输入选择数据库类型、输入dsn名:、选择服务器、连接数据库的方式、输入数据库的登陆用户和密码->测试连接,如果测试成功的话,那么你的dsn就建立好了,我的dsn名为Sqlserver.使用的是sqlserver7.0,以 “sa”登陆,密码为空。这些东西都是后面要用道的!
  好了下面让我们来看程序代码: (该代码已经通过运行)
//###########################################################
//代码开始
import java.sql.*;
//加载java数据连接包,java基本所有的数据库的调用的都在这个东西里面
public class InsertCoffees {
public static void main(String args[]) {
String url = "jdbc:odbc:sqlserver";
//取得连接的url名,注意sqlserver是dsn名
Connection con;
//实例化一个Connection对象
Statement stmt;
String query = "select * from col_link";
//选择所有的Col_link表中的数据输出
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//加载jdbc-odbc桥驱动
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
//加载jdbc-odbc桥错误
System.err.println(e.getMessage());
//其他错误
}
try {
con = DriverManager.getConnection(url, "sa", "");
//数据库连接
stmt = con.createStatement();
//Create 一个声明
stmt.executeUpdate("CREATE TABLE col_link (sitename varchar (20) NULL ,siteurl varchar (50) NULL) ");
//执行了一个sql语句生成了一个表col_link的表
stmt.executeUpdate("insert into col_link values('ASP中华网','http://www.aspcn.com')");
stmt.executeUpdate("insert into col_link values('永远到底有多远','http://xuankong.com')");
//执行一个insert into语句
stmt.executeUpdate("update col_link set siteurl='http://www.aspcn.com/xuankong/xuankongt.jpg' where siteurl='http://xuankong.com'");
//执行一个update语句,更新数据库
ResultSet rs = stmt.executeQuery(query);
//返回一个结果集
System.out.println("Col_link表中的数据如下(原始数据)");
//下面的语句使用了一个while循环打印出了col_link表中的所有的数据
System.out.println("站点名 "+" "+"站点地址");
System.out.println("---------------"+" "+"----------------");
while (rs.next()) {
String s = rs.getString("sitename");
String f = rs.getString("siteurl");
//取得数据库中的数据
System.out.println(s + " " + f);
/*String t = rs.getString(1);
String l = rs.getString(2);
System.out.println(t + " " + l);*/
/*jdbc提供了两种方法识别字段,一种是使用getXXX(注意这里的getXXX表示取不同类型字段的不同的方法)获得字段名,
第二种*是通过字段索引,在这里我把第二种方法注释了*/
/*你可以访问这个连接获得getxxx的用法:http://java.sun.com/docs/books/tutorial/jdbc/basics/_retrievingTable.html*/
}
stmt.close();
con.close();
//上面的语句关闭声明和连接
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
//显示数据库连接错误或者查询错误
}
}
}
//代码结束
Statement
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
How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL Commands in MySQL: Practical ExamplesSQL Commands in MySQL: Practical ExamplesApr 14, 2025 am 12:09 AM

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

How does InnoDB handle ACID compliance?How does InnoDB handle ACID compliance?Apr 14, 2025 am 12:03 AM

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)