Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert string to SQL using C#

I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#

My code:

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

builder.DataSource = "testtetstet.database.windows.net";
builder.UserID = "PW";
builder.Password = "000000000";
builder.InitialCatalog = "test";

using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
    String query = "INSERT INTO dbo.amir (theDate,Hostname,IP) VALUES (@theDate,@hostName, @IP)";

    using (SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.Add("@theDate");
        command.Parameters.Add("@hostName");
        command.Parameters.Add("@IP");

        connection.Open();
        var result = command.ExecuteNonQuery();

        // Check Error
        if (result < 0)
            Console.WriteLine("Error inserting data into Database!");
    }
}

What I'm trying to do is, insert 3 strings in to the sql database but it seems that it does not work!!

"@hostname"is a string which contains the computer name "@IP" is a string which contains the IP adress "@theDate" is a DateTime string which display date and time.

What am I doing wrong?

like image 1000
Amir Avatar asked Dec 11 '22 05:12

Amir


1 Answers

You are not setting the value of parameter.You should either Use Parametrs.Add like this:

command.Parameters.Add("@IP", SqlDbType.VarChar).Value = "0.0.0.0";
//equals to:
//command.Parameters.Add("@IP", SqlDbType.VarChar); 
//command.Parameters["@IP"].Value = "0.0.0.0";

or (not recommended):

command.Parameters.AddWithValue("@IP", "0.0.0.0");
like image 76
Ashkan Mobayen Khiabani Avatar answered Dec 12 '22 22:12

Ashkan Mobayen Khiabani