100 likes | 214 Views
Database Programming. Dr. John Abraham. Data Sources. Data source specifies the source of the data for an application. Click on Data from Menu Choose show data sources Add a data source Point to the directory where it is located Choose the table you want
E N D
Database Programming Dr. John Abraham
Data Sources • Data source specifies the source of the data for an application. • Click on Data from Menu • Choose show data sources • Add a data source • Point to the directory where it is located • Choose the table you want • Drag the data source to the form to bind it to the program.
Data source Configuration Wizard • Choose a data source type • Click on database • Choose a database model • Choose dataset • Choose the database object starting with the computer name • Creates a connections string like this: • "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\transcript.mdb“ • Test the connection before continuing.
Add connection • Make sure to choose the type of database you are using such as Microsoft Access, SQL, Oracle, ODBC, etc. • Express edition does not give all the options.
Choose database objects for the data source • Choose the table you want • Choose the fields you want by checking • Give the dataset a name
Using a data source • If you drag and drop a table from the Data Sources Visual studio adds a DataGrid View control. • If you already have a dragridView control on the from, just drag the table onto it.
Sample code. • This worked on my laptop with SQL-express installed. private void btnSave_Click(object sender, EventArgs e) { SqlConnection cs = new SqlConnection("Data Source=ABRAHAM-LAPTOP:SQLEXPRESS1; Initial Catalog=csharp; Integrated Security=True"); cs.Open(); //MessageBox.Show(cs.State.ToString()); SqlDataAdapter dc = new SqlDataAdapter(); dc.InsertCommand = new SqlCommand("INSERT INTO CONTACTS VALUES (@Fname, @Lname,@Tele)",cs); dc.InsertCommand.Parameters.Add("@Fname", SqlDbType.VarChar).Value=textFname.Text; cs.Close(); }
Code for LINQ to SQL This also worked on my notebook computer with SQL express installed. • static void Main(string[] args) { DataClasses1DataContext mine = new DataClasses1DataContext(); var st = from CONTACT in mine.CONTACTs select CONTACT; foreach (var s in st) System.Console.WriteLine(s.Fname + s.Lname + s.Tele); System.Console.ReadKey(); } Here is the output • John Abraham 3550Pearl Brazier 3455