search
HomeDatabaseMysql Tutorial用ODBC连接MySQL和ASP.NET_MySQL

用ODBC连接MySQL和ASP.NET_MySQL

Jun 01, 2016 pm 02:11 PM
mysqldeal withInstalldatabaseserverstructureconnect

ODBC


  被认为是“世界上最流行的开放源代码数据库”的MySQL从最初一个毫不起眼的低成本数据库服务器成长为驱动庞大Web网站和重要商业系统的服务器经历了一个漫长的历程。但是,如果你是一位ASP.NET的开发人员,那么你总会碰到一个不如意的地方:MySQL原先是为UNIX平台上的应用程序设计的,所以对Windows的支持处于次要地位。
  
  但是现在,Windows版本的MySQL已经具备了与UNIX版本同样的特性和稳定性,而且它被认为是用于Windows开发的可行的数据库服务器。现在让我们来看看你可以如何使用ODBC在.NET框架内连接MySQL数据库。
  
  安装
  下载和安装Windows版的MySQL。安装很简单——只用按照提示你就能够立即安装好并开始运行了。如果碰到了问题,可以去MySQL的论坛看看,寻求帮助和解决方法。
  
  要把ASP.NET和MySQL连接起来,你需要使用ODBC.NET。一般来说,ODBC.NET的DataProvider是标准的.NET框架(1.1及以上的版本)的一部分,所以会和后者一起自动安装好。
  
  一旦确认ODBC.NET安装完毕,你就需要下载用于MySQL的ODBC驱动程序。再强调一遍,MySQL的开发人员都很乐意提供帮助——他们都在自己的Web网站上提供了这些驱动程序。在下载文件的时候你可以看看FAQ文档,它会列出在往系统里安装MySQL ODBC驱动程序期间可能碰到的所有的问题。
  
  都做好了?现在就让我们从一些代码开始吧。
  
  用ASP.NET连接MySQL
  我最喜欢做的一件事情是阅读,而且当我没有编写像本文一样的教学文章时,我会找一个安静的角落补全参考书目表。不幸的是,我不是一个组织性很强的人,所以这常常搞得一团糟。
  
  那这又与我们今天要谈的话题有什么关系呢?嗯,这是我第一个例子的开场白,这个例子就是创建一个像列表A里的书籍的数据库。
  
  要建立这个表格,就要使用下面的SQL查询:
  
  CREATE TABLE `books` (
  `id` int(5) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL default '',
  `authors` varchar(255) NOT NULL default '',
  `year_of_publication` year(4) NOT NULL default '0000',
  `date_added` date NOT NULL default '0000-00-00',
  PRIMARY KEY (`id`)
  ) TYPE=MyISAM;
  而要执行这个查询,就要使用MySQL安装目录下的“bin”文件夹的命令行客户端软件“mysql.exe”。下面就是具体命令:
  
  c:\mysql\bin>mysql -u guest -p test
  Enter password: ******
  Welcome to the MySQL monitor. Commands end with ; or \g.
  Your MySQL connection id is 13 to server version: 4.0.12-nt
  
  Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
  
  mysql> CREATE TABLE `books` (
  ->  `id` int(5) NOT NULL auto_increment,
  ->  `title` varchar(255) NOT NULL default '',
  ->  `authors` varchar(255) NOT NULL default '',
  ->  `year_of_publication` year(4) NOT NULL default '0000',
  ->  `date_added` date NOT NULL default '0000-00-00',
  ->  PRIMARY KEY (`id`)
  -> ) TYPE=MyISAM;
  Query OK, 0 rows affected (0.02 sec)
  
  一旦“书籍(books)”表格创建好了,就可以开始插入数据了。列表B里列举了一些项目。现在,用ASP.NET做同样的事情——执行SELECT查询(列表C)并在浏览器里显示结果。如果一切都没有问题——MySQL服务器在运行,MySQL ODBC驱动程序安装正确,“书籍”表格含有数据——你就应该会看到像图A里的页面。
   用ODBC连接MySQL和ASP.NET_MySQL
  现在让我们来更加仔细地看看代码列表。所有东西一开始都要调入所需要的.NET库。由于我正在使用ODBC.NET连接MySQL服务器,所以需要调用System.Data.Odbc和System.Data程序集。一旦程序集调用完毕,就要定义连接字符串,这包括修改服务器(Server)、数据库(Database)、uid和pwd变量以体现本地服务器的设置。
  
  在创建了OdbcConnection()和OdbcCommand()对象之后,初始化本地的OdbcDataReader()对象,从“书籍”表格取回数据。这个对象提供了一条ExecuteReader()命令来执行SQL查询。剩下的就是例行公事了:将OdbcDataReader()指定为dbgooks DataGrid的数据源,并调用DataGrid()对象的DataBind()方法将两者绑定起来。
  
  当然,你可以对数据库做更多的事情——向表格里插入(INSERT)数据、使用更新(UPDATE)修改它们、用删除(DELETE)命令获得记录的网格,或者就根据WHERE语句里面的条件选择子集。
  
  异常的处理
  现在让我们来看一些异常的处理(列表D)方法,以对付程序员经常碰到的一些无法预见的状况。正如你会注意到的,列表D使用了嵌套try-catch结构来提供多级别的错误处理。下面列出来的一段代码应该有助于你更好地理解它:
  
    }%>
  现在首先让我们看看里层的“try-catch”结构。这个结构用来处理创建OdbcCommand()或者OdbcDataReader()对象的实例时可能发生的错误。如果数据库里不存在“书籍”表格,就有可能发生这样的错误。如果发生了这样的错误,“catch”部分就会发出一个新的Exception()。里层的“try-catch”结构的“finally”块然后就会在脚本进一步执行之前关闭OdbcConnection()对象。
  
  动作然后就转到外层的“try-catch”结构。外层的结构能够处理两种类型的异常——OdbcException()或者是一般的Exception()。前者在由于某种原因无法打开到数据库服务器的连接或者脚本无法将OdbcConnection()对象实例化的时候产生,而后者用来处理内层“try-catch”结构所产生的异常。无论发生两种情况中的哪一种,都会有一个ASP.NET标签服务器控件向用户显示相应的错误消息。
  
  图B向你显示,当脚本尝试连接到一个不存在的数据库服务器时所发生的事情(这个由外层的“try-catch”结构来处理)。
   用ODBC连接MySQL和ASP.NET_MySQL
  图C向你显示的错误信息会在脚本尝试访问一个不存在的数据库表格时出现(要注意,内层“try-catch”结构产生的异常会由外层结构来处理):
  用ODBC连接MySQL和ASP.NET_MySQL
  以上就是关于如何使用MySQL和ASP.NET的DataGrid服务器控件的介绍。关于你可以如何使用这两种技术还有更多的内容可谈;所以我希望本文和上面提供的其他参考资源能够帮助你对此有个初步的了解。
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
When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

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
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools