gpt4 book ai didi

c# - "Cannot implicitly convert type IDbConnection to SqlConnection"

转载 作者:行者123 更新时间:2023-11-30 13:22:25 26 4
gpt4 key购买 nike

我需要一些帮助

我尝试将 INSERT 插入到我的 SQL 数据库中,但我做不到,因为在此代码行中给我一个错误:

 commandoSQL.Connection = dbcon;

我收到这个错误:

Assets/NGUI/Scripts/Interaction/ChamarVariavel.cs(43,29): error CS0266: Cannot implicitly convert type System.Data.IDbConnection' toSystem.Data.SqlClient.SqlConnection'. An explicit conversion exists (are you missing a cast?)"

我希望有人能帮我解决这个问题。

谢谢

我的代码:

public class ChamarVariavel : MonoBehaviour {

public UISlider slider;

// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {
}

void OnGUI(){
// Connection DB
string connectionString = "Data Source=(local);Initial Catalog=Test;User ID=******;Password=*******";

IDbConnection dbcon;

dbcon= new SqlConnection(connectionString);

dbcon.Open();
//DB Online

float x = slider.value * 100;
GUI.Label(new Rect( 570, 238, 70, 30 ), "(" + x.ToString("f2") + ")");

string qInsert = string.Format(@"INSERT INTO Fuel (fuel) VALUES ('{0}')", x);

SqlCommand commandoSQL = new SqlCommand(qInsert);

commandoSQL.Connection = dbcon;

try
{
commandoSQL.ExecuteNonQuery();
}
catch (Exception ex)
{
GUI.Label(new Rect( 300, 40, 300, 300 ), ex.ToString());
}

dbcon.Close();
//DB offline
}
}

最佳答案

错误字面上告诉你问题所在,你需要显式转换对象,因为SqlCommand正在寻找SqlConnection,考虑这样做:

new SqlCommand(qInsert, (SqlConnection)dbcon);

并删除这一行:

commandoSQL.Connection = dbcon;

另一种选择是将 dbcon 定义为 SqlConnection:

SqlConnection dbcon

然后你可以这样做:

new SqlCommand(qInsert, dbcon);

最后,看看blog post我前一段时间写过;您需要改变您使用对象的方式。

关于c# - "Cannot implicitly convert type IDbConnection to SqlConnection",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24209038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com