Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is a general approach to do basic operations with mysql database. I assume that you know how to setup your mysql database. if not you can find many info about it on google. I also assumed that you have a table on your mysql database named "table" which has following columns: id, name, address.</p> <pre><code> // Connection String private const string ConnStr = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;" + "Database=test;uid=root;pwd=;option=3"; // DataBinding private void BindDataGrid() { using(OdbcConnection con = new OdbcConnection(ConnStr)) using(OdbcCommand cmd = new OdbcCommand("SELECT * FROM Sample", con)) { con.Open(); DataGrid1.DataSource = cmd.ExecuteReader( CommandBehavior.CloseConnection | CommandBehavior.SingleResult); DataGrid1.DataBind(); } } // Insert Operation private void InsertInfo() { if(CheckIsAddNameValid()) { HtmlTable2.Visible = false; using(OdbcConnection con = new OdbcConnection(ConnStr)) using(OdbcCommand cmd = new OdbcCommand("INSERT INTO sample" + "(name, address) VALUES (?,?)", con)) { cmd.Parameters.Add("@name", OdbcType.VarChar, 255).Value = TextBox3.Text.Trim(); cmd. Parameters.Add("@address", OdbcType.VarChar, 255).Value = TextBox4.Text.Trim(); con.Open(); cmd.ExecuteNonQuery(); BindDataGrid(); } } } // Update Operation private void UpdateInfo(int id, string name, string address) { using(OdbcConnection con = new OdbcConnection(ConnStr)) using(OdbcCommand cmd = new OdbcCommand("UPDATE sample " + "SET name = ?, address = ? WHERE ID = ?", con)) { cmd.Parameters.Add("@name", OdbcType.VarChar, 255).Value = name; cmd.Parameters.Add("@address", OdbcType.VarChar, 255).Value = address; cmd.Parameters.Add("@ID", OdbcType.Int).Value = id; con.Open(); cmd.ExecuteNonQuery(); } } // Update Operation private void DeleteInfo(int id) { using(OdbcConnection con = new OdbcConnection(ConnStr)) using(OdbcCommand cmd = new OdbcCommand("DELETE " + "FROM sample WHERE ID = ?", con)) { cmd.Parameters.Add("@ID", OdbcType.Int).Value = id; con.Open(); cmd.ExecuteNonQuery(); } } </code></pre> <p>if you do not have a table on your database use this script to create the database in this example:</p> <pre><code>CREATE TABLE sample ( id int AUTO_INCREMENT NOT NULL, name varchar(45) NOT NULL, address varchar(45) NOT NULL, PRIMARY KEY(id) ) GO </code></pre> <p>BindDataGrid function shows the result of the query in datagrid. In general you can put the result of any query to a list and then bind it to the datagrid with the following code:</p> <pre><code>List&lt;string&gt; AllStudents = getAllStudents(); dataGrid1.datasource = AllStudents; dataGrid1.databind(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload