C#操作MySQL数据库-----HelloWorld
这里采用在visual studio 2010中通过MySql.Data.dll、MySql.Web.dll来连接mysql数据库,
之后便进行数据的插入和查询。
Program.cs文件内容如下:
- 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();
- }
- }
- }
- }
- }
运行结果如下:
数据库中内容为:
查询结果为:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。