Sei sulla pagina 1di 4

C# Window form application connected to SQL Server (Group work: week 8)

The purpose of this assignment is to connect C# with SQL Server, and to design a Window form application to query and
display the various content of a SQL Server database.

A Database connection is a facility in computer science that allows client software to communicate with database server
software, whether on the same machine or not. A connection is required to send commands and receive answers. No
command can be performed against a database without an "open and available" connection to it. Connections are built
by supplying an underlying driver or provider with a connection string, which is a way of addressing a specific database
as well as user authentication credentials. Once a connection has been built it can be opened and closed at will, and
properties can be set. The Connection String is composed of a set of key/value pairs as dictated by the data access
interface and data provider being used.

Two major connection types exist: ODBC (Open Database Connectivity) and JDBC (Java Database Connectivity)

ODBC is used mainly with Microsoft Products, our case here.

JDBC is used with Java Programmers who use Java software (like Netbeans) to connect to Databases. They won’t connect
to Microsoft databases but rather other ones like mysql and Oracle. MySQL, the most popular Open Source SQL
database management system, is developed, distributed, and supported by Sun Microsystems. Oracle is an advanced,
efficient and expensive RDBMS designed for huge database applications.

We will be using ODBC SQL Connection to connect C# to SQL Server 2005.

We will be using also the two previous weather tables we worked on so far.

You have 2 ways to make a connection from C# to Sql Server

 The wizard way (easier but with restrictions)


(Go to tools, connect to database, press next, choose MS Sql Server database and then specify the server name,
finally add all tables to the dataset.
 The direct coding way. Sample code:

try
{
SqlConnection conn = new SqlConnection("Data Source=WS100921\\SQL2005;Initial
Catalog=Project;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("SQL Query", conn);
SqlDataReader reader = cmd.ExecuteReader();
String S1="",S2="";
Console.WriteLine("Column Name:\t{0} {1}", reader.GetName(0).PadRight(15),
reader.GetName(1));
Console.WriteLine("Data Type:\t {0} {1}",
reader.GetDataTypeName(0).PadRight(15), reader.GetDataTypeName(1));
while (reader.Read())
{
S1=reader.GetInt32(0).ToString();
S2 = reader.GetInt32(1).ToString();
listBox1.Items.Add(S1 + '\t' + S2);
Console.WriteLine("\t\t\t\t{0} {1}", S1.PadRight(15),S2);
}
reader.Close();

}
catch (Exception ed)
{
Console.WriteLine("Sql Error Occurred: " + ed);
}

Data Source is the Sql Server name, find its name when connecting.
Initial Catalog is the database name
SqlCommand: you write here the Sql command you want to execute.
SqlDataReader: where your results as a dataset are stored
The above code will output to the console and in a listBox the content of the table
composed of two integer fields
Try catch block: always include the sql connection declaration and its execution in
a try catch block. This will prevent the application from crashing unexpectdedly if
the database server encounters an error. The variable of type exception will be
displayed explaying the error nature

SqlDataReader is suitable for queries generating a dataset (select). Other methods include
cmd.ExecuteNonQuery() for an insert into or a delete, and cmd.ExecuteScalar() for
queries generating only one value (computation)

Now create a C# window form application in Visual Studio.net 2005, add a main form where you will place a data grid to
display the table contents.

Add a button to move you to another form. The code is:

Form formdata;
formdata = new Form2(S);
formdata.Show();

Form2 is the second form (form1 was the first, the main one)

S is a parameter you want to pass from a form to another one. For example you need to pass
the city name.

Add this parameter S as a class variable and to the constructor of form2.

In form2, add meaningful labels and several list boxes to display information.

In the form2 load method, open the connection (above code) and execute the following
queries:
 Find the highest and average recorded temperature, display them in 2 labels
 Find the number of measurements recorded by year, display them in a listbox
 Find the number of measurements recorded by year for a specific city, display them
in another listbox
 Find Highest Recorded Weather parameters per month, display also in another listbox.
Go back to form1. Display latitude and longitude in String format for a specific
city. While retrieving information about a city, display the latitude as being
West(positive) or East(negative). Also for longitude (display North for positive and
South for negative). Practice here with some C# code, take care for null values
which are acceptable for latitude and longitude. Also display the average values of
all weather parameters for a specific city in different labels.

 In form1, add a button to go to a new form (form3) which is for adding a new city.
Add in form3 labels for the 3 city table parameters. Add 3 textboxes to fill in for
new values and a button for submission. Upon clicking, you have to check if the
entered city is already in the database and prevent the insertion without letting
the database server issues a primary key violation constraint which will lead to an
application crash. Also check that the other 2 values are indeed real values and
possible (find what I mean by possible, an internet search is needed). Finally make
the insertion by issuing an appropriate Sql statement.
 Repeat the insertion for a measurement on a specific date for a specific cities.
Take care about all possible invalid cases.
 This is a ONE week assignment, don’t improve it by adding more features as the next
Web assignment is much more important. You will get full grade if you implement the
above requirements, but you will be penalized if you are late.

Notes:

 You can make use of other controls, check the toolbox to see what you can add.
 You can use the SqlDataAdapter to access your database
 Make use of stored procedures, with and without parameters
 The datetime datatype is very efficient in Sql Server. It encloses day, month, year and the time. If time is not
specified while inserting, it takes the default value of 12:00am, midnight, time 0. To access the year, use
year(Date); to access the month, use month(date). To round decimal values use round(thevalue,x) where x is the
number of decimal digits.
 This assignment lets you practice on Sql Server DBMS and on C#.
 If you know Java and would like to use it to design your project, you can use it to solve this assignment. The
requirements are the same but instead of using Sql Server, you use mysql (available console DBMS in the lab)
and netbeans 6.5 (downloaded on some computers). You need the mysql JDBC connector which is available
with the instructor. Java uses JDBC to connect to databases, whereas Microsoft products use ODBC_ADO.net
to connect to databases
Web application Connected to SQL Server (Group work 2 weeks: week 9 and 10)
Design a Web application using Visual Studio.net with ASP.net files and C# or using Netbeans with JSP files.

What to show in your application is similar with what you have shown in the previous programming assignment.

Make use of at least the two tables you created previously for the window application. Add similar controls to your web
pages, including the outputs of the SQL queries you have performed previously. Many things are just similar.

The minimum requirements in this web application are the same you did in the previous window programming
assignment.

At the end of this assignment and in the appendix 2, you have a tutorial about ASP.net and related technologies
together with some examples.

Notes:
ASP.net provides a rich set of built in controls that you can directly make use of. You can just drag the control on the
empty page and assign to it events or connect to database. Also Netbeans 6.5 offers a similar set of controls by choosing
the framework Visual Java Server Faces. You can also make use of servlets with Netbeans

When using Netbeans, choose Java web application, accept all default values and choose the above framework.

When using Visual Studio.net, choose new web site, then ASP.net Web site with language visual C#, it will create a
default aspx file where you can drag your controls. The corresponding C# file will have an extension of aspx.cs.

In both kinds of web applications, you can add html files with JavaScript, CSS, and forms.

You will use MS SQL Server with Visual Studio.net or mysql with Netbeans.

 This assignment lets you practice on Sql Server DBMS and on ASP.net with C#.
 Moreover it is an integral part of your project. It will be of a great help in your project implementation.
 Make use of stored procedures, useful also for the projects.
 These above requirements are the minimum you are supposed to do. They will worth a grade in the eighties. To
get a grade in the nineties, additional features must be added. They include more controls and more SQL
programming. To get a 100 as all students like, your assignment must be spectacular including user friendliness,
colorful and nicely designed. Yes your instructor likes “colors”, it is sometimes the key to sell a software.
 This assignment is a team group work. One student per group has to come and present it. The instructor may ask
some questions where he expects fast and confident answers otherwise grades may be deducted.

What you have to submit: You will present and submit only the Web application. The windows application won’t be
graded so that it does not prevent you working on the project

Potrebbero piacerti anche