c# – “无法将类型IDbConnection隐式转换为SqlConnection”
发布时间:2020-12-16 00:11:14 所属栏目:百科 来源:网络整理
导读:我需要一些帮助. 我尝试将INSERT插入我的SQL数据库,但我不能,因为在此代码行中给出了一个错误: commandoSQL.Connection = dbcon; 我收到此错误: Assets/NGUI/Scripts/Interaction/ChamarVariavel.cs(43,29): error CS0266: Cannot implicitly convert type
我需要一些帮助.
我尝试将INSERT插入我的SQL数据库,但我不能,因为在此代码行中给出了一个错误: commandoSQL.Connection = dbcon; 我收到此错误:
我希望有人可以帮助我. 谢谢 我的代码: 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我写了一会儿;你需要改变你使用对象的方式. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |