首页 > 代码库 > C#操作MySQL数据库-----HelloWorld
C#操作MySQL数据库-----HelloWorld
这里采用在visual studio 2010中通过MySql.Data.dll、MySql.Web.dll来连接mysql数据库,
之后便进行数据的插入和查询。
Program.cs文件内容如下:
C#代码
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using MySql.Data.MySqlClient;
- using System.Data;
- namespace DatabaseProgram
- {
- class Program
- {
- static string mysqlConnectionString = "Server=localhost;Database=csharp;Uid=root;Pwd=admin";
- static void Main(string[] args)
- {
- InsertData();
- SelectData();
- }
- //向数据库插入数据
- public static void InsertData()
- {
- MySqlConnection conn = new MySqlConnection(mysqlConnectionString);
- MySqlCommand command;
- conn.Open();
- try
- {
- command = conn.CreateCommand();
- command.CommandText = "INSERT INTO phoneBook(id,name,mobile) VALUES(@id,@name,@mobile)";
- command.Parameters.AddWithValue("@id", 2);
- command.Parameters.AddWithValue("@name", "yangjianzhou");
- command.Parameters.AddWithValue("@mobile", "1234567890");
- command.ExecuteNonQuery();
- }
- catch (Exception)
- {
- }
- finally
- {
- if (conn.State == ConnectionState.Open)
- {
- conn.Close();
- }
- }
- }
- //从数据库中读取数据
- public static void SelectData()
- {
- MySqlConnection conn = new MySqlConnection(mysqlConnectionString);
- conn.Open();
- MySqlDataReader dataReader = null;
- MySqlCommand command = null;
- try
- {
- command = conn.CreateCommand();
- command.CommandText = "SELECT * FROM phoneBook";
- dataReader =command.ExecuteReader();
- Console.WriteLine();
- while (dataReader.Read())
- {
- Console.WriteLine("id={0}, name={1}, mobile={2}", dataReader.GetInt16(0), dataReader.GetString(1), dataReader.GetString(2));
- Console.WriteLine();
- }
- }
- catch (Exception)
- {
- }
- finally
- {
- if (!dataReader.IsClosed)
- {
- dataReader.Close();
- }
- if (conn.State == ConnectionState.Open)
- {
- conn.Close();
- }
- }
- }
- }
- }
运行结果如下:
数据库中内容为:
查询结果为:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。