L0ky L0ky - 17 days ago 6x
SQL Question

"Cannot implicitly convert type IDbConnection to SqlConnection"

I need some help please.

I tried make an

into my SQL database but I can't because give me an error in this code line:

commandoSQL.Connection = dbcon;

I get this error:

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

I hope somebody can help me with this.


My code:

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);

//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;

catch (Exception ex)
GUI.Label(new Rect( 300, 40, 300, 300 ), ex.ToString());

//DB offline


The error is literally telling you the problem, you need to explicitly cast the object because the SqlCommand is looking for a SqlConnection, consider doing this:

new SqlCommand(qInsert, (SqlConnection)dbcon);

and remove this line:

commandoSQL.Connection = dbcon;

Another option is to just define dbcon as a SqlConnection:

SqlConnection dbcon

and then you could do this:

new SqlCommand(qInsert, dbcon);

Finally, have a look at a blog post I wrote a while back; you need to change how you're using your objects.