Sunday, March 10, 2013

C# + SQL Example #1

* Gets max row count
* Inserts a new row (value number greater than max rows)
* Displays row values

[CODE]


            string connString = "Server=localhost;Database=cshptest;Uid=root;"; // Select DB
            MySqlConnection conn = new MySqlConnection(connString);
            MySqlCommand command = conn.CreateCommand();
            // Command to count the rows
            conn.Open();
            command.CommandText = "SELECT COUNT(*) FROM csdat";
            int rows = Convert.ToInt32(command.ExecuteScalar());
            int newrows = rows + 1;
            conn.Close();
            // Insert a new data row, with the value greater than last index value (ex. 5 + 1 = 6)
            command.CommandText = "Insert into csdat (id,dataT) values('" + newrows + "','" + newrows + "');";
            conn.Open();
            command.ExecuteNonQuery();
            conn.Close();
            MySqlDataReader reader;
            // Read data in each row
            for (int i = 0; i <= rows; i++)
            {
                string cnt = i.ToString();
                conn.Open();
                command.CommandText = "Select dataT from csdat where id=" + cnt; // Select column from table
             
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    MessageBox.Show(reader["dataT"].ToString()); // extract data from column
                }
                conn.Close();
            }


[/CODE]

No comments:

Post a Comment

My Facebook Music group

  🎧𝅘𝅥𝅲 M̾U̾S̾I̾X̾ ♭🎧