Sunday, February 12, 2012

Cant insert data into sql database

hi
It seems that my code can insert data into memory, but not into the database. What I mean is that after "insert data", I can "read data",
which I just insert. When I check the actual database table, it didn't
get updated.

I am using VS 2005 and table designer. Regarding to this problem, is
it related to any setting of setup of the database? I check the code,
and I have no idea how it occurs.

private static string connectionString = null;
private static SqlConnection connection = null;
private static string commandString = null;
private static SqlCommand command = null;
private static SqlDataReader reader = null;

static void Main(string[] args)
{
connectionString = ConfigurationManager
.ConnectionStrings["appDatabase.Properties.Settings.databaseConnection String"]
.ConnectionString;

connection = new SqlConnection(connectionString);

try
{
// Insert data
commandString = @."INSERT INTO userTable
(userID, permissionLevel, mobile, emailAddress, mailAddress, pager) VALUES(1, 2, '123', 'aa@.a.com', 'oz', 'no')";
SqlCommand command = new SqlCommand(commandString, connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();

// Read data
commandString = @."select * from userTable";
command = new SqlCommand(commandString, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["permissionLevel"].ToString());
}
connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

regards
figo2476have u got any sqlexception when u tried to insert data?|||Hi Figo

Welcome to the forum :D

So the select code at the bottom works? Are you certain the conection string in your config file defo matches the database you have been accessing manually? There is no setting (certainly in SQL Server) that would do what you think is happening.|||Have you tried wrapping your transaction with...

BEGIN TRAN
...your sql statement...
COMMIT

?|||have you tried using stored procedures?|||Server=.\SQLExpress;AttachDbFilename=|DataDirector y|mydbfile.mdf;Database=dbname;Trusted_Connection= Yes;"

I figured out the problem by relacing the |DataDirectory| with the physical path of the mdf file. I double check this on the web & find that both of methods should work without a problem. I am not sure why this occurs

It seems that when using virtual path, the data is sored in Memory, not actually in the database.

figo2476

No comments:

Post a Comment