C # Connection Query database __ Database

Source: Internet
Author: User
Tags readline

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Collections.Generic;
Using System.Text;

Namespace Database Learning
{
Class Program
{
static void Main (string[] args)
{

Use lightweight SqlDataReader to display data
Specify the connection string for the SQL Server provider
String connstring = "Server=192.168.99.45;database =northwind;uid =sa;pwd=1";

To establish a Connection object

SqlConnection sqlconn = new SqlConnection (connstring);
Open connection
Sqlconn.open ();

Specify a command object for the connection above
SqlCommand Thiscommand = Sqlconn.createcommand ();
Thiscommand.commandtext = "Select Customerid,companyname from Customers";

Executes DataReader for the specified Command object
SqlDataReader thissqldatareader = Thiscommand. ExecuteReader ();

As long as there is data
while (Thissqldatareader.read ())
//{
Output data
Console.WriteLine ("\t{0}\t{1}", thissqldatareader["CustomerId"], thissqldatareader["CompanyName"]);
//}
Turn off Read
Thissqldatareader.close ();
Close connection
Sqlconn.close ();
Console.ReadLine ();

Displaying data using a dataset

Query string
String Thiscommand = "Select Customerid,companyname from Customers";

Create the SqlDataAdapter object with two parameters, one for the query string and one for the connection object
SqlDataAdapter sqldap = new SqlDataAdapter (Thiscommand,sqlconn);

Creating a DataSet Object

DataSet Thisdataset = new DataSet ();

Fill the DataSet with the SqlDataAdapter fill method with two parameters, one for the created dataset instance and one for the filled table

Sqldap.fill (Thisdataset, "customers");

Show Query Results

foreach (DataRow therow in thisdataset.tables["Customers"). Rows)

{
Console.WriteLine (therow["CustomerID"] + "T" + therow["CompanyName"]);
}
Sqlconn.close ();

Console.ReadLine ();

}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.