简体   繁体   English

C#:插入 mysql 表

[英]C#: Insert into mysql table

I am trying to connect to mysql from c# and insert into an existing table in a db.我正在尝试从 c# 连接到 mysql 并插入到数据库中的现有表中。
The C#-Connector is installed and I added the following references:安装了 C#-Connector 并添加了以下引用:

C:/program files (x86)/mysql/connector net 8.0/assemblies/v4.5.2/mysql.data.dll
C:/program files (x86)/mysql/connector net 8.0/assemblies/v4.5.2/mysql.web.dll

I tried changing the @s to ?s which made no difference.我尝试将 @s 更改为 ?s ,这没有任何区别。

using MySql.Data.MySqlClient;

namespace ConnectToMysql
{
    class Program
    {
        static void Main(string[] args)
        {
            string txtTitle = "SharpConnector";
            string txtAuthor = "Myself";
            int myRating = 5;

            string myConnectionString = "Server=localhost;Database=mydb;Uid=root;Pwd=mypw";

            MySqlConnection mconnection = new MySqlConnection(myConnectionString);
            MySqlCommand cmd;
            //the next line causes an unhandled exception
            mconnection.Open();

            cmd = mconnection.CreateCommand();
            cmd.CommandText = "insert into books(title, author, myrating)values(@title,@author,@myrating)";
            cmd.Parameters.AddWithValue("@title", txtTitle);
            cmd.Parameters.AddWithValue("@author", txtAuthor);
            cmd.Parameters.AddWithValue("@myrating", myRating);
            cmd.ExecuteNonQuery();

            mconnection.Close();
        }
    }
}

Error: Unhandled exception.错误:未处理的异常。 Cannot print exception string because >Exception.ToString() failed.无法打印异常字符串,因为 >Exception.ToString() 失败。

The C#-Connector is installed and I added the following references:安装了 C#-Connector 并添加了以下引用:

C:/program files (x86)/mysql/connector net 8.0/assemblies/v4.5.2/mysql.data.dll C:/program files (x86)/mysql/connector net 8.0/assemblies/v4.5.2/mysql.web.dll C:/program files (x86)/mysql/connector net 8.0/assemblies/v4.5.2/mysql.data.dll C:/program files (x86)/mysql/connector net 8.0/assemblies/v4.5.2/mysql.web .dll

This is not the appropriate way to add references to a C# project;这不是向 C# 项目添加引用的适当方法; it won't necessarily add all the dependencies (which is probably why you're getting the exception).它不一定会添加所有依赖项(这可能是您收到异常的原因)。

Remove those references, then (assuming you're using Visual Studio) right-click your project in Solution Explorer and choose Manage NuGet Packages.删除这些引用,然后(假设您使用的是 Visual Studio)在解决方案资源管理器中右键单击您的项目并选择管理 NuGet 包。 In the "Browse" tab, enter MySql.Data (or MySqlConnector for a more modern alternative), select it, then click "Install".在“浏览”选项卡中,输入MySql.Data (或MySqlConnector以获得更现代的替代方案),选择它,然后单击“安装”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM