Hello everyone,
Just new to C#. I am trying to use visual studio 2005 and trying to connect to a database and create a basic application. Would appreciate some help.
I went to create a new application and selected, the langug C# and it created 2 files default.aspx and default.cs
Now time to use the some code.
- First hurdle, trying to connect to the database at school
- Put a text box, enter a name in the box and then a button. On clicking the button I want to search for the name from a database and display
it in a grid. such as name, address and which class is the student taking. The database has the info on name address and class.
Please help me to get started. Thanks!
Bechir BejaouiRank #144 · 15.9K pointsPosted Dec 9, 2008, 2:22 PM EST
Former memberPosted Dec 15, 2008, 6:01 AM EST
First try to connect to the database and try retreive one or two values....
The code is..
for Ms access:
using System.Data;
using System.Data.OleDb;
using System;
public class Adojet{
public static void Main(){
String strResult ;
String strConnect ;
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=books.mdb";
OleDbConnection con=null;
OleDbDataReader objDR =null;
String strSelect ;
strSelect = "SELECT * FROM BookList WHERE ISBN LIKE '1861003%'";
try{
con = new OleDbConnection(strConnect);
con.Open();
//OleDbCommand cmd = new OleDbCommand(strSelect, con);
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText=strSelect;
objDR= cmd.ExecuteReader();
//con.Close();
while (objDR.Read())
{
strResult = " " + objDR["ISBN"] + " " + objDR["Title"] + " " + objDR["PublicationDate"] ;
Console.WriteLine(strResult);
}
}catch (Exception objError)
{
Console.WriteLine(objError);
}
finally
{
objDR.Close();
con.Close();
}
}
}
For Sql
using System.Data;
using System.Data.SqlClient;
using System;
public class adoSQLClient{
public static void Main(){
String strResult ;
String strConnect ;
strConnect = "server=doit;database=northwind;uid=sa;pwd=sa";
String strSelect ;
strSelect = "select firstname from employees";
try{
SqlConnection con = new SqlConnection(strConnect);
con.Open();
SqlCommand cmd = new SqlCommand(strSelect, con);
SqlDataReader objDR ;
objDR = cmd.ExecuteReader();
while (objDR.Read())
{
strResult = " " + objDR["firstname"] ;
Console.WriteLine(strResult);
}
objDR.Close();
con.Close();
}catch (Exception objError) { Console.WriteLine(objError);
}
}
}
Hope it helps....
Please be free to ask any doubts...