I am new to console application. Now i wrote a sample function for insert values in database. There is no problem in my database connection. But my valuse are not inserting in table. Please find the issue and let me know.
This is my code
static void Main(string[] args)
{
try
{
string sConnectionString = "Data Source=my ipaddress;Network Library=DBMSSOCN;Initial Catalog=db;user id=user;Password=password";
string sSQL = "";
using (var connection = new SqlConnection(sConnectionString))
{
connection.Open();
Console.WriteLine("OK");
for (int i = 1; i <= 5; i++)
{
sSQL = "INSERT INTO test " +
"(id) " +
"VALUES (" + i + ")";
Console.WriteLine(i + " inserted successfully");
}
SqlCommand objCmd = new SqlCommand(sSQL, connection);
}
}
catch (DbException)
{
Console.WriteLine("NOT OK");
}
}
You're not executing the command at all - you're creating a SqlCommand
, and then doing nothing with it. You need to call ExecuteNonQuery()
.
However, you should also stop building the SQL like that. You should start using parameterized SQL right now. Something like this:
using (var connection = new SqlConnection(sConnectionString))
{
connection.Open();
var sql = "INSERT INTO test (id) VALUES (@id)";
using (var command = new SqlCommand(sql, connection))
{
// Adjust this to match the type of the id field
var parameter = command.Parameters.Add("@id", SqlDbType.Int);
for (int i = 1; i <= 5; i++)
{
parameter.Value = i;
command.ExecuteNonQuery();
}
}
}
See more on this question at Stackoverflow