如何在c#中连接到mysql数据库并模仿SELECT, UPDATE和INSERT函数

本文关键字:SELECT UPDATE 函数 INSERT 数据库 连接 mysql | 更新日期: 2023-09-27 18:15:42

如何在c#中连接到MySQL数据库,并使用它来访问数据库中的UPDATE值,数据库中的INSERT值和数据库中的SELECT

此外,是否有可能获得行的值,并在c#中模仿这个PHP ?

$query = mysql_query("SELECT * FROM foo WHERE foo = 'foo');
while($row = mysql_fetch_assoc($query)) {
$foo1 = $row['foo1'];
//and so on
}

如何在c#中连接到mysql数据库并模仿SELECT, UPDATE和INSERT函数

你必须下载MySql Connector/. net。

如何使用c#和MySQL connector/net连接到MySQL 5.0 !列出了一些示例代码,这些代码与您所拥有的非常相似:

private void button1_Click(object sender, System.EventArgs e)
{
  string MyConString = "SERVER=localhost;" +
                       "DATABASE=mydatabase;" +
                       "UID=testuser;" +
                       "PASSWORD=testpassword;";
  MySqlConnection connection = new MySqlConnection(MyConString);
  MySqlCommand command = connection.CreateCommand();
  MySqlDataReader Reader;
  command.CommandText = "select * from mycustomers";
  connection.Open();
  Reader = command.ExecuteReader();
  while (Reader.Read())
  {
    string thisrow = "";
    for (int i= 0;i<Reader.FieldCount;i++)
      thisrow+=Reader.GetValue(i).ToString() + ",";
    listBox1.Items.Add(thisrow);
  }
  connection.Close();
}

首先要了解ADO。它们负责建立数据库会话,执行命令(查询)和检索结果,之后你必须下载MySql连接器API(数据提供程序API)并学习MySql连接器的提供程序类。

Connector/NET Examples

1-添加引用到我的项目:MySql.Data.MySqlClient

2-安装MySQL for Visual Studio下载链接:https://dev.mysql.com/downloads/windows/visualstudio/

注意:要创建Mysql数据库,请点击链接:

https://www.freesqldatabase.com/

代码:

string stconnetionString = "Server=Server name; Port=port number; 
         Database= DB name; Uid=User namw; Pwd=password;";
MySqlConnection conn = new MySqlConnection(stconnetionString);
try
{
    conn.Open();
    MySqlCommand mycmd = conn.CreateCommand();
    mycmd.CommandType = CommandType.Text;
    mycmd.CommandText = "insert into Student(columes name) values(.....)";
    mycmd.ExecuteNonQuery();
    conn.Close();
    MessageBox.Show("Saved", "Window Application ", MessageBoxButtons.OK, MessageBoxIcon.Information);
    clear();
}
catch (Exception)
{
    throw;
}