C#操作数据库-----HelloWorld
程序员文章站
2023-12-23 11:11:10
...
这里采用在visual studio 2010中通过MySql.Data.dll、MySql.Web.dll来连接mysql数据库,
之后便进行数据的插入和查询。
Program.cs文件内容如下:
运行结果如下:
数据库中内容为:
查询结果为:
之后便进行数据的插入和查询。
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(); } } } } }
运行结果如下:
数据库中内容为:
查询结果为: