【发布时间】:2014-06-13 15:32:18
【问题描述】:
我需要一些帮助。
我尝试在我的 SQL 数据库中创建一个INSERT,但我不能,因为在此代码行中给我一个错误:
commandoSQL.Connection = dbcon;
我收到此错误:
Assets/NGUI/Scripts/Interaction/ChamarVariavel.cs(43,29):错误 CS0266:无法隐式转换类型
System.Data.IDbConnection' toSystem.Data.SqlClient.SqlConnection'。存在显式转换(您是否缺少演员表?)”
我希望有人可以帮助我。
谢谢
我的代码:
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
}
}
【问题讨论】:
-
该错误与插入无关 - 它与
Connection属性的分配有关。关注相关问题。您应该能够摆脱强制转换 (commandoSQL.Connection = (SqlConnection)dbcon;),因为它是作为new SqlConnection(connectionString)创建的,尽管使用更好的类型变量(var或SqlConnection)可以完全避免这种情况。 -
@user2864740 您在评论中几乎回答了他的问题。如果你真的回答了它,那么它可能会给你加分,但也让人们更容易看到正确的答案,代码格式看起来更好等等。但是你是对的 ;-)
-
我建议使用 IDbConnection 中的 CreateComman 方法。 msdn.microsoft.com/en-us/library/…
标签: c# sql sql-server unity3d