ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/dotnet-java/lab_asp_odbc.docx · web viewchange the...

18
Tutorial for using the MySQL ODBC Connector to connect MySQL with ASP.NET If your computer doesn’t contains MySQL, download it from here: http://www.mysql.com/downloads/ Download the “MySQL Community Server 5.5”, http://www.mysql.com/downloads/mysql/5.5.html “MySQL Workbench 5.2”, http://www.mysql.com/downloads/workbench/5.2.html and “Connector/ODBC” http://dev.mysql.com/downloads/connector/odbc/ If you already have it in your computer, or if you are familiar with mysql to build tables, you can just download an ODBC connecter from here and then install it: When you done the installation, go to “Start” -> “All Programs” - > “MySQL” -> “MySQL Workbench”

Upload: dangdan

Post on 25-May-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Tutorial for using the MySQL ODBC Connector to

connect MySQL with ASP.NETIf your computer doesn’t contains MySQL, download it from here:http://www.mysql.com/downloads/

Download the “MySQL Community Server 5.5”, http://www.mysql.com/downloads/mysql/5.5.html

“MySQL Workbench 5.2”,http://www.mysql.com/downloads/workbench/5.2.htmland “Connector/ODBC”http://dev.mysql.com/downloads/connector/odbc/

If you already have it in your computer, or if you are familiar with mysql to build tables, you can just download an ODBC connecter from here and then install it:

When you done the installation, go to “Start” -> “All Programs” -> “MySQL” -> “MySQL Workbench”

Page 2: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Click the , give a Connection Name, here it is Connection_MySQL. Click the

“Store in Value” button next to the Password, the root’s initial password is “root”. Click OK, OK.

Then double click the “Connection_MySQL”.

Page 3: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Then, click the “New Schema”

Here, we name it Books, click “Apply”->”Apply SQL”->”Finish”->”Close”

Page 4: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

You will see a new MySQL Schema named “Books” showing like this after clicking the refresh button.

Change the “Default” in “Object Browser” to “books”

Copy and paste the following code in to “SQL Query” window

CREATE TABLE `Books` ( `ID` int(11) NOT NULL auto_increment, `Name` varchar(100) NOT NULL default '', `Authors` varchar(100) NOT NULL default '',

Page 5: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

`Publisher` varchar(100) NOT NULL default '', `ISBN` varchar(100) NOT NULL default '', `Copyright` int(11) NOT NULL, PRIMARY KEY (`ID`));

INSERT INTO books VALUES (1,' Java Web Development with NetBeans IDE', 'Kai Qian, Daniel Moreau', 'Linus', '1-60797-188-7',2011);INSERT INTO books VALUES (2,' Embedded Software Development with C', 'Kai Qian, David den Haring, Li Cao', 'Springer', ' 978-1-4419-0605-2',2010);INSERT INTO books VALUES (3,' Software Architecture And Design Illuminated ', 'Kai Qian, Xiang Fu, LiXin Tao, Jorge Diaz-Herrera, Chong-wei Xu', ' Jones & Bartlett', ' 9780763754204 ',2009);INSERT INTO books VALUES (4,' Web Development with JavaScript and AJAX Illuminated ', 'Richard Allen, Kai Qian, LiXin Tao, Xiang Fu', 'Jones& Bartlett','0763754891', 2009);INSERT INTO books VALUES (5,' Java Web Development Illuminated', 'Kai Qian, Richard Allen, Mia Gan, Bob Brown', 'Jones & Bartlett ', '0763734233', 2007);INSERT INTO books VALUES (6,'Component Oriented Programming', 'Andy Wang, Kai Qian', 'Wiley', '0471644463',2005);

Click the button to run the SQL Query Code.

You will see the report like this:

The database table has done!

Page 6: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Then open the Visual Studio 2010, click “File”->”New Web Site”, choose “Visual C#”, “ASP.NET Empty Web Site”, here we name it MySQL_ODBC_Lab, click OK.

Open the “web.config” fileAdd the following code after the </system.web>:

<connectionStrings> <add name="MySQLConnStr" connectionString="DRIVER={MySQL ODBC 5.1 Driver};Database=books;Server=localhost;UID=root;PWD=root;"/> </connectionStrings>

Remember to change “DRIVER”, “Database”, ”Server”, ”UID”, ”PWD” to your own according to the your MySQL.Then right click in the “Solution Explorer”->”Add New Item”, choose ”Visual C#”, “Web Form”, name it “Default.aspx”. Click “Add”.Open the “Default.aspx.cs” which is under the file ”Default.aspx”(Click the small triangle to see it)

Add the using statement as follows: using System.Configuration;using System.Data.Odbc;Then add the following code into the “Page_Load” function:

try {

Page 7: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString)) { connection.Open(); using (OdbcCommand command = new OdbcCommand("SELECT name FROM books", connection)) using (OdbcDataReader dr = command.ExecuteReader()) { while (dr.Read()) Response.Write(dr["name"].ToString() + "<br />"); dr.Close(); } connection.Close(); } } catch (Exception ex) { Response.Write("An error occured: " + ex.Message); }

Here are some explanations for the codes://OdbcConnection - Provides an ODBC connection to a database.//OdbcCommand - Will execute an SQL command using an existing OdbcConnection.//OdbcDataReader - Will provide fast access to the data which the OdbcCommand will bring us.

Run the website, and have a look at the output. It should contain a bunch of names from our books table, or which ever table you're using.Here is the result:

Page 8: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Now we will add a drop downlist.Go to file “Default.aspx”, add the following codes after “<div>“ <asp:DropDownList runat="server" id="DropDownList1" datavaluefield="id" datatextfield="name" />

Then change the code in “Default.aspx.cs”, with a small modification:

try { using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString)) { connection.Open(); using (OdbcCommand command = new OdbcCommand("SELECT id, name FROM books", connection)) using (OdbcDataReader dr = command.ExecuteReader()) { DropDownList1.DataSource = dr; DropDownList1.DataBind(); dr.Close();

} connection.Close(); } } catch (Exception ex) { Response.Write("An error occured: " + ex.Message); }

Only 2 things have changed from the last example: We've added a field to the query (the id field), and we have changed the loop to a couple of databinding lines. The first one assigns the datasource of the dropdown list to our datareader, and the second one tells the dropdown list to perform the databinding. That's all we need, which you will see if you run the website. The dropdown list will be filled with names from our test table.

Page 9: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Now, let’s add a grid view to show all the data from the table “books”. Go to the Design view of Default.aspx, drag the GridView to Default.aspx from ToolBox, it should be in the Data class

If you can’t find it from Toolbox, you can right click in the Toolbox, click “Choose Item” to add the GridView Component.

Page 10: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following
Page 11: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Then right click on the GridView you just added, choose “Show Smart Tag”

Click the dropdown list of Choose Data Source, choose <New data source…>

Click Dtatbase-> OK

Page 12: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Click-> New Connection

Change the Data Source to “Microsoft ODBC Data Source”->OK

Click->Use Connection String, copy the connection string from your file ”web.config” like this:DRIVER={MySQL ODBC 5.1 Driver};Database=books;Server=localhost;UID=root;PWD=root;

Then click “Build”

Page 13: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Click OK->OK->Next

Name the connection as “mybooksConnectionString”, click Next

Page 14: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Click , click Next

Add the following SQL statement:Select * from books;

Then click Next->Text Query->Finish

Page 15: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Visual Studio will help you to add a SqlDataSource on the Default.aspx, run it!Here is the result:

We have almost done it, let’s add a search function to query the books on the website.Drag a TextBox and a Button from the Toolbox into Default.aspx

Page 16: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

Double click on the Button, copy and paste the following code into Button1_Click function: string res = "SELECT * FROM books WHERE ( Name like '%" + TextBox1.Text.ToString() + "%') Order by ID"; SqlDataSource1.SelectCommand = res; GridView1.DataSourceID = "SqlDataSource1"; GridView1.DataBind();

Run the website, here is the result:

Let’s do the final function, change the Drop Down List and let the GridView show the corresponding data of the selected Book’s nameDrag a button from ToolBox, put it next to the Drop Down List, double click the new button.Add the following statement to the Button2_Click function:

string selectedItem = DropDownList1.SelectedItem.ToString(); string res = "SELECT * FROM books WHERE ( Name ='" + selectedItem + "')"; SqlDataSource1.SelectCommand = res; GridView1.DataSourceID = "SqlDataSource1"; GridView1.DataBind();

Then go to the Page_Load function, add an “if” statement for the whole function. (please google search “IsPostBack”, it will tell you why we need it):

The code will like this:

if (!IsPostBack) { try { using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString)) {

Page 17: ksuweb.kennesaw.eduksuweb.kennesaw.edu/~kqian/DOTNET-Java/Lab_ASP_ODBC.docx · Web viewChange the “Default” in “Object Browser” to “books” Copy and paste the following

connection.Open(); using (OdbcCommand command = new OdbcCommand("SELECT id, name FROM books", connection)) using (OdbcDataReader dr = command.ExecuteReader()) { DropDownList1.DataSource = dr; DropDownList1.DataBind(); dr.Close();

} connection.Close(); } } catch (Exception ex) { Response.Write("An error occured: " + ex.Message); } }

Run the website, and test the new button. Here is the result: