27
How to use MySql With C# Ross Sherman 1

How to use MySql With C#

  • Upload
    tasya

  • View
    60

  • Download
    4

Embed Size (px)

DESCRIPTION

How to use MySql With C#. Ross Sherman. Using MySql. MySql is free. You could download it from: http://dev.mysql.com/downloads/ When the setup wizard completes check Launch the MySQL Instance Configuration Wizard and click Finish - PowerPoint PPT Presentation

Citation preview

Page 1: How to use  MySql  With C#

1

How to use MySql With C#

Ross Sherman

Page 2: How to use  MySql  With C#

Using MySqlMySql is free. You could download it from: http://dev.mysql.com/downloads/

When the setup wizard completes check Launch the MySQL Instance Configuration Wizard and click FinishChoose Development Machine and leave the defaults as they areChoose a passwordAdd at least one user accountChoose defaults for the rest of the screens Once installed, start the MySQL Workbench; click Open Connection to Start Querying

Page 3: How to use  MySql  With C#

create database videostore;

use videostore;

create table moviesrented (personid int(4),movieid int(4) );

create table customer (id int(4), lastname varchar(12), firstname varchar(12),

email varchar(12), pass varchar(12) );

create table movies (id int(4),

moviename varchar(20), numberavailable int (3));

Creating a new database in MySql; creating new tables in the database

From Professor Gueorguieva’s database lecture:SQL ServerData Type

Corresponding C# or .NET FrameworkData Type

bit bool

datetime dateTime

decimal decimal

float double

int int

money decimal

nchar string

nvarchar string

Page 4: How to use  MySql  With C#

Inserting values into your database’s tablesINSERT INTO customerVALUES ('1212','Stan','Gundy','[email protected]','coach'),('1132','Phil','Jackson','[email protected]','eleven');

INSERT INTO moviesVALUES ('1333','Mission_Impossible','3'),('1334','Jack_Reacher','4'),('1335','Admission', '2');

INSERT INTO moviesrentedVALUES ('1212','1334'),('1212','1335'),('1132','1334');

Page 5: How to use  MySql  With C#

Querying your databaseSelect *from customer;

select max(id) from customer;

select idfrom movieswhere id = 1212;

select *from customerwhere firstname like ‘P%’;

select customer.id as IDNameCustID, customer.firstname, moviesrented.persionid, movies.movienamefrom moviesrented, customer, movieswhere moviesrented.persionid = customer.idand moviesrented.movieid = movies.id;

Page 6: How to use  MySql  With C#

To delete a row in a table:deletefrom moviesrentedwhere movieid = 1212;

To delete all rows from a table: deletefrom moviesrented;

To drop a table from your database:drop table moviesrented;

To add a new column to an existing table: alter tablecustomeradd birthdate date;

Deleting rows, dropping tables, and adding columns

Page 7: How to use  MySql  With C#

1) You might run into a problem when you try to delete rows. To fix this problem go to the Edit tab in the MySql Workbench and click on preferences.

2) Once you have clicked on preferences, click on SQL Queries and make sure that “Safe Updates” is unchecked. If it is checked, uncheck it, press ok, and restart MySql for the change to take affect.

If you run into a problem deleting rows:

Page 8: How to use  MySql  With C#

Connecting Visual Studio to MySql:

First, Create a new Windows Forms Project.

Page 9: How to use  MySql  With C#

9

Next, you will need to add MySql.data as a reference.

Adding MySQL.data as a reference:

In the Solution Explorer, click on the name of your presentation, right click on references, click on add reference.

Page 10: How to use  MySql  With C#

After clicking on add reference you will be taken to the reference manager form.In Reference Manager form, select Extensions, find MySql.Data and press the check box next to MySq.Data, them click on ok.

Page 11: How to use  MySql  With C#

11

At this point, you have created a database and you have connected that database to MySql.

Now, you need to query and manipulate the data from your database in your C# code.

Go to the design section of your newly created windows form and add a button to it. Double click the button to go to the code.

Page 12: How to use  MySql  With C#

At the top, include the line: using MySql.Data.MySqlClient;

Page 13: How to use  MySql  With C#

In the button’s code include the following lines: private void button1_Click(object sender, EventArgs e) { try { string connectionInfo = "datasource = localhost; port = 3306; username = root; password = csi";

MySqlConnection connect = new MySqlConnection(connectionInfo);

connect.Open(); MessageBox.Show("Connected"); connect.Close(); } catch(Exception ex) {

MessageBox.Show(ex.Message); } }

Page 14: How to use  MySql  With C#

To find out what to put into: string myConnection = "datasource = localhost; port = 3306; username = root; password = csi";go to the MySql workbench and press ctrl+u.The following screen should appear:

The password is the password you created. If you are using the school’s computer the password is csi.

Page 15: How to use  MySql  With C#

How to use MySql to create a login.

1) Place two labels, two textboxes, and a button on your form.

2) Double click on the button to edit the code for the button.

In my code on the next slide:FirstName’s textbox is textBox1 and Password’s textbox is textBox2 (I renamed the text but not the actual textboxes). The login button is button1.

Page 16: How to use  MySql  With C#

private void button1_Click(object sender, EventArgs e) { try {

string connectionInfo = "datasource = localhost; port = 3306; username = root;”

+ “password = csi"; MySqlConnection connect = new MySqlConnection(connectionInfo);

MySqlCommand SQLCommand1 = new MySqlCommand("select * from videostore.customer” + “where firstname = '"+ textBox1.Text +"‘” + “and pass = '"+ textBox2.Text +"';", connect); MySqlDataReader reader; connect.Open(); reader = SQLCommand1.ExecuteReader(); int count = 0;

while (reader.Read()) {

count = count + 1; }

Check the entered firstname and password with the customer table of the videostore database.

Page 17: How to use  MySql  With C#

if (count == 1) { MessageBox.Show("Firstname and password is correct"); } else if (count > 1) { MessageBox.Show("Duplicate Firstname and password. You are not allowed access"); } else MessageBox.Show("Firstname and password is not correct"); connect.Close(); } // end of try block catch(Exception ex) { MessageBox.Show(ex.Message); }} // end of login button code

Login Button Code Continued

Page 18: How to use  MySql  With C#

Adding additional forms to your Visual Studio project

First, right click on presentation. Then, go down to add and click on new item. Select windows form and click add.

Page 19: How to use  MySql  With C#

The code that makes clicking on the login button take you to the second form.

Go back to the code for the login button in slide 17. Inside of if (count == 1) add the 3 lines of code that are in purple:

if (count == 1) { MessageBox.Show("Firstname and password is correct"); this.Hide(); Form2 f2 = new Form2(); f2.ShowDialog(); }

Page 20: How to use  MySql  With C#

Querying and inserting values into a databaseFirst, add 4 labels, 4 textboxes, and a button to your second form.Then double click on enter data and enter the following code to find the largest id that any customer has: private void button1_Click(object sender, EventArgs e)

{ string connectionInfo = "datasource = localhost; port = 3306;" + "username = root; password = pawsox11";

MySqlConnection connect = new MySqlConnection(connectionInfo);

MySqlCommand SQLCommand1 = new MySqlCommand(" select max(id) as 'id‘” + ” from videostore.customer;", connect); MySqlDataReader reader; connect.Open(); reader = SQLCommand1.ExecuteReader();

Page 21: How to use  MySql  With C#

int id = 1; while (reader.Read()) { id = reader.GetInt32("id") + 1; MessageBox.Show("This is" + id); } connect.Close(); string k = "stop"; MySqlCommand SQLCommand2 = new MySqlCommand("insert into”

+ ”videostore.customer(id,lastname,firstname,email,pass)" + "values('" + id + "','" + k + "','" + k + "', '" + k + "', '" + k + "');", connect); connect.Open(); reader = SQLCommand2.ExecuteReader(); connect.Close();} // close the enter data button code

Querying and inserting values into a database continuedIn the code below, you are adding one to the max(id) – the largest customer id – and you are inserting that value, along with four copies of string k, into the customer table of the videostore database:

Page 22: How to use  MySql  With C#

Adding an exit button

Add a new button to the second form. Double click on the button. Add the following code to the button: Application.Exit();

Page 23: How to use  MySql  With C#

Adding things to a list box from a database Add a listbox and a new button to your second form. Double click on the new button (I named the text of the button “put into list box” but the button’s name is button2 – the exit button is button 3 in my code).

Page 24: How to use  MySql  With C#

private void button2_Click(object sender, EventArgs e){

string connectionInfo = "datasource = localhost; port = 3306;" + "username = root; password = pawsox11"; MySqlConnection connect = new MySqlConnection(connectionInfo);

MySqlCommand SQLCommand1 = new MySqlCommand("select * from ” + “videostore.customer as c,"

+ "videostore.moviesrented as mr," + "videostore.movies as m where c.id =“

+ “mr.personid and m.id" + "= mr.movieid and c.firstname = " + "'" + textBox1.Text + "';", connect);

Because the scope of this button doesn’t include objects created in the other button in this form you will have to create a new object of class MySqlConnection. In the code below I gave the new object of class MySqlConnection the same name as it had in the other button: connect. The SQL query in this code is the same SQL query that I introduced in slide 5.

Adding things to a list box from a database continued

Page 25: How to use  MySql  With C#

Adding things to a list box from a database continued MySqlDataReader reader; try { connect.Open(); reader = SQLCommand1.ExecuteReader(); while (reader.Read()) { string movieName, firstNameinC; int id = 1; movieName = reader.GetString("moviename"); firstNameinC = reader.GetString("firstname"); id = reader.GetInt32("id");

listBox1.Items.Add(firstNameinC + " " + movieName + " " + id); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } // end of button2’s code

Previously, I have shown you how an object of the class MySqlDataReader (I named the object reader) reads one thing from the database. But, as you can see in this code, objects of the MySqlDataReader class could get many things from a database. Here, I got a moviename from the movie table, the firstname from the customer table, and the id from the customer table.

Page 26: How to use  MySql  With C#

//include the using MySql line at the topusing MySql.Data.MySqlClient;

//create an object of MySqlConnection with the string containing datasource, etc as a parameterstring connectionInfo = "datasource = localhost; port = 3306; username = root; password = pawsox11";MySqlConnection connect = new MySqlConnection(connectionInfo);

//create an object of MySqlCommand with the SQL Query as the first parameter and the object of MySqlConnection //as the second parameter MySqlCommand SQLCommand1 = new MySqlCommand("select * from videostore.customer;”,connect);try {

//open the connection using the MySqlConnection object connect.Open();//use a DataReader to process each recordMySqlDataReader reader;reader = SQLCommand1.ExecuteReader();while (reader.Read()) { //do something with each record }

} catch (Exception er) {//do something with the exception}//always close the connection connect.Close();

Summary

Page 27: How to use  MySql  With C#

ReferencesFrom the Stanford Online Database Course:Introduction to SQL: http://www.youtube.com/watch?feature=player_embedded&v=wxFmiRwXcQYbasic-select-statement:http://www.youtube.com/watch?feature=player_embedded&v=4IxirOdp6bwtable-variables-set-operators:http://www.youtube.com/watch?v=-BCCy5Z6i-s&feature=player_embeddedsubqueries-in-where:http://www.youtube.com/watch?v=IJPXosPGLTU&feature=player_embeddedsubqueries-in-from-select:http://www.youtube.com/watch?v=8OCAxk1Rybg&feature=player_embedded

Professor Chi's database class website:http://163.238.35.144/~chi/CSC715/CSC715.htmlProfessor Chi's SQL part 1 tutorial:http://163.238.35.144/~chi/CSC424/SQL/SQL%20Tutorial%20--%20Part%201%20MySQL.htm

C# Visual Studio with MySql Tutorials:http://www.youtube.com/playlist?list=PLS1QulWo1RIZrmdggzEKbhnfvCMHtT-sA

Professor Gueorguieva's Database with C# lecture:http://www.cs.csi.cuny.edu/~natacha/TeachSpring_2013/CSC330/CSharp/Lec5/DatabasesCSharp.pdf