user2827904
user2827904

Reputation: 167

SQL server express, cannot read or write in C#

I have a code written that automatically adds and reads information from my SQL Server 2012 Express table, Logins. But it wont work, here is the code:

private void Form1_Load(object sender, EventArgs e)
    {
        SqlConnection myConnection = new SqlConnection("user id=myComputer;" + "server=MYCOMPUTER-PC\\SQLEXPRESS;" +
                "Trusted_Connection=yes;" + "database=loginTest; " + "connection timeout=5");
        try
        {
            myConnection.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        SqlCommand myCommand = new SqlCommand("INSERT INTO dbo.Logins Values ('John','Password','Admin')", myConnection);
        try
        {
            SqlDataReader myReader = null;
            SqlCommand myCommand1 = new SqlCommand("select * from Logins",
                                                     myConnection);
            myReader = myCommand1.ExecuteReader();
            while (myReader.Read())
            {
                MessageBox.Show(myReader["Column1"].ToString());
                MessageBox.Show(myReader["Column2"].ToString());
            }
        }
        catch (Exception ex1)
        {
            MessageBox.Show(ex1.ToString());
        }
    }

I have debugged the program and it all seems to go through fine, it skips over :

        {
            MessageBox.Show(myReader["Column1"].ToString());
            MessageBox.Show(myReader["Column2"].ToString());
        }

for some reason, and it doesnt write the values i told it to.

Can anyone tell me why? Im a beginner at SQL, so go easy please :)

PS It doesnt fire out any error codes or exceptions

Upvotes: 1

Views: 129

Answers (2)

King King
King King

Reputation: 63347

You Logins table doesn't have any records, if you mean you want to try inserting some record first to test, it's this line causing your problem:

SqlCommand myCommand = new SqlCommand("INSERT INTO dbo.Logins Values ('John','Password','Admin')", myConnection);
myCommand.ExecuteNonQuery();//Do this to insert something into your Logins first.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502016

it skips over [...]

Presumably that's because there's no data to read, so myReader.Read() just returns false.

it doesnt write the values i told it to.

You don't actually tell it to write anything. You create a SqlCommand to insert data, but you never execute it. You need to use myCommand.ExecuteNonQuery. You should also use using statements for the commands, the connection and the reader, to make sure they get closed properly.

Upvotes: 4

Related Questions