Reputation: 15
I am new to C# and databases. I am connecting to my local database server using CreateConnection()
method. I am trying to insert data into database table. When I read this data from SQL Server Management Studio using select query I am not able to get data back from table. However, I am able to read this data when I execute sql query from C# program. I doubt that the table that my C# program is accessing and the table created in SQL Server Management Studio are not same even if they have same path and same name.
Code for CreateConnection
:
public void CreateConnection()
{
Console.WriteLine("CreateConnection");
myConnection = new SqlConnection("Data Source=(local); Database=MyServerDB;Server=ATLW732FV000169\\SQLEXPRESS;Integrated Security=True; connection timeout=30");
{
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Code for SQL query:
primary_cmd = "INSERT INTO flightData (flightNum, Country) VALUES ('555','xyz');"
using (SqlCommand myCommand = new SqlCommand(primary_cmd, myConnection))
{
try
{
int rows = myCommand.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine(e);
}
}
I am not getting any kind of exception while inserting data into database. when I run same insert query in SQL Server Management Studio it works fine and inserts data in table. Additionally, I am able to read the inserted data from table from C# program. It looks like C# is connecting to some temporary database table and inserting into it.
Upvotes: 0
Views: 264
Reputation: 2356
Sounds like your connection string is wrong as it is not making the connection you are expecting. Everything else seems right. I don't think I have ever seen DataSource=(local) and Server=... in the same connection string. Maybe try something like:
new SQLConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=MyServerDB;server=(local)")
Or:
new SQLConnection("SERVER=ATLW732FV000169\\SQLEXPRESS;Trusted_Connection=Yes;DATABASE=MyServerDB")
Upvotes: 1
Reputation: 21
Perhaps implicit transactions are off in your database. In this case you need to commit the transaction by excuting another command:
COMMIT TRANSACTION
Upvotes: 0