- 论坛徽章:
- 0
|
1.安装好MYSQL
2.熟悉MySQL一些简单命令的使用方法:比如:
show databases;
show tables;
connect [tablename];
show version();
3.针对.NET进行MySQLConnect
先下载MySQL/dotNET安装包
使用MySQL.data.dll
//C#代码
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace myodbc3
{
class mycon
{
static void Main(string[] args)
{
MySqlConnection conn = new MySqlConnection("server=127.0.0.1;user id=root; password=guilee; database=test; pooling=false");
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from table1";
MySqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
Console.WriteLine(dr[0].ToString());
}
conn.Close();
}
}
}
MySQL Connector/J
介绍一些一般性的JDBC背景知识。
使用DriverManager接口连接到MySQL
在应用服务器外使用JDBC时,DriverManager类将用于管理连接的建立。
需要告诉DriverManager应与哪个JDBC驱动建立连接。完成该任务的最简单方法是:在实施了java.sql.Driver接口的类上使用Class.forName()。对于MySQL Connector/J,该类的名称是com.mysql.jdbc.Driver。采用该方法,可使用外部配置文件来提供连接到数据库时将使用的驱动类名和驱动参数。
在下面的Java代码中,介绍了在应用程序的main()方法中注册MySQL Connector/J的方式:
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; // Notice, do not import com.mysql.jdbc.*// or you will have problems!(注意,不要导入com.mysql.jdbc.*,否则// 将出现问题!) public class LoadDriver { public static void main(String[] args) { try { // The newInstance() call is a work around for some // broken Java implementations Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { // handle the error }}
在DriverManager中注册了驱动后,通过调用DriverManager.getConnection(),能够获得与特殊数据库相连的连接实例。
示例:从DriverManager获得连接
在本示例中,介绍了从DriverManager获得连接实例的方法。对于getConnection()方法,有一些不同的特性。关于如何使用它们的更多信息,请参阅与JDK一起提供的API文档。
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; ... try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=monty&password=greatsqldb"); // Do something with the Connection .... } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); }
一旦建立了连接,它可被用于创建语句和PreparedStatements,并检索关于数据库的元数据。
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/23701/showart_400112.html |
|