|
|
2008年11月21日
Code
//构造一个DataView对象,传递死个函数
DataView dv=new DataView(dt,"country='Germany'","country",DataViewRowState.CurrentRows);
第一个参数:DataTable,第二个:对DataTable内容进行筛选的筛选器,
第三个是排序列,最后一个参数是指定要在视图中包含的行的类型.
System.Data.DataViewRowState是一个枚举类型:
Added----新行
CurrentRows----当前行,包含未修改的,修改的,新的
Deleted--被删除的行
ModifiedOriginal--已修改过的原来的版本
ModifiedCurrent--被修改过的当前版本
None-- 没有行
OriginamRows--原来的行。包括为修改的和删除的行
unchanged--为修改的行
foreach (DataRowView drv in dv)
{
for (int i = 0; i < dv.Table.Columns.Count; i++)
{
Console.Write(drv[i]+""t");
} Console.WriteLine();
}
//////////////////////////
DataRow--DataTable中的一行
DataViewRow--DataView中的单行
//DataView是DataTable内容的动态表示,与Sql视图一样,它不保存数据!
DataView是建立在DataTable基础上的,DataView.Table 属性可以得到此DataView对应的那个DataTable。
DataView的行叫DataRowView,
可以从DataRowView直接通过 DataRowView.Row 属性得到此DataRowView对应的DataRow

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Server=zhuobin;uid=sa;pwd=zhuobin;database=Northwind");
string sql = @"select contactname,country from customers";
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sql,conn);
//create the dataset and fill it
DataSet ds = new DataSet();
da.Fill(ds,"customers");
//get the data from the datatable
DataTable dt = ds.Tables["customers"];
//create the dataView
DataView dv = new DataView(dt,"country='Germany'","country",DataViewRowState.CurrentRows);
//display the data from data view
foreach (DataRowView drv in dv)
{
for (int i = 0; i < dv.Table.Columns.Count; i++)
{
Console.Write(drv[i]+"\t");
} Console.WriteLine();
}
}
catch (SqlException ex)
{
Console.WriteLine("The error:{0}", ex.Message);
}
finally
{
conn.Close();
}
Console.ReadLine();
}
}
}
在调用Fill()方法时,如果连接没有打开,fill()就自动打开,在数据填充完毕后关闭它.
如果在调用Fill()方法时打开了连接,fill()就使用该连接,But won't close it after it uesd it !
虽然数据集完全独立于与数据库和连接,但是使用数据集并不意味着和数据库断开连接.
如果要在断开的情况下运行就可以用数据集,但是在填充他之前不要打开l连接(或者如果连接上打开的就先关闭它.).数据集并不表示在断开或打开连接的操作!
应该在Finally{}中Conn.Close();因为他在已关闭的条件下调用也不会出错!
Code
//先创建数据适配器,
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=new SqlCommand(sql,conn);
//创建和填充数据集
DataSet ds=new DataSet();
da.Fill(ds,"Customers");
//每个查询返回一个数据集,每个结果都保存在单独的DataTable中.第一个显示地命名Customers,第二个表达默认名词为Customers1.
//从数据集的Tables属性获得DataTables对象集合
DataTableCollection dtc=ds.Tables;
在显示第一个表时:
string fl="country='Germany'";//sql where
string srt="CompanyName desc";//sql desc

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("server=zhuobin;uid=sa;pwd=zhuobin;database=Northwind");
string sql1 = @"select * from customers ";//Notice:add a space after the string sql1
string sql2 = @"select * from products where unitprice<10";
string sql = sql1 + sql2;
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "customers");
//Console.WriteLine("I love you !");
//get the table collections
DataTableCollection dtc = ds.Tables;//the tables collections of the ds
//display data from the first table
Console.WriteLine("Result from the customers tables:");
Console.WriteLine("CompanyName".PadRight(20),"ContactName".PadRight(23)+"\n");
//set display filter
string fl = "country='Germany'";
//set sort
string srt = "Companyname";
//display the filtered and sorted data
foreach (DataRow row in dtc["customers"].Select(fl, srt))
{
Console.WriteLine("{0}\t{1}",row["companyname"].ToString().PadRight(25),row["contactname"].ToString());
}
//display the data from the second table
Console.WriteLine("\n-----------------------------------------------------");
Console.WriteLine("The result from products :");
Console.WriteLine("ProductName".PadRight(20),"UintPrice".PadRight(21));
//display data
foreach (DataRow row in dtc[1].Rows)
{
Console.WriteLine("{0}\t{1}",row["productname"].ToString().PadRight(25),row["unitprice"].ToString());
}
}
catch (SqlException ex)
{
Console.WriteLine("The error {0}", ex.Message);
}
finally
{
conn.Close();
}
Console.ReadLine();
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Server=zhuobin;uid=sa;pwd=zhuobin;database=Northwind");
String sql = @"select productname,unitprice from products where unitprice<20 and productname='Chai'";
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
da.Fill(ds,"products");
DataTable dt=ds.Tables["products"];
//display data
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("The row is "+row.ToString());
Console.WriteLine(dt.Rows.Count.ToString());
foreach (DataColumn col in dt.Columns)
{
Console.WriteLine(row[col]);//mean that rows["productname"]
Console.WriteLine("The column is "+col.ToString());//output the field!
} Console.WriteLine("".PadLeft(20,'='));
}
}
catch (SqlException ex)
{
Console.WriteLine("Error:{0}", ex.Message);
}
finally
{
conn.Close();
}
Console.ReadLine();
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("server=zhuobin;uid=sa;pwd=zhuobin;database=northwind");
string sql = @"select companyname,contactname from customers where contactname like 'M%'";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql,conn);
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("\t{0}{1}","CompanyName".PadRight(25),"ContactName".PadRight(20));
Console.WriteLine("\t{0}{1}","===========".PadRight(25),"===========".PadRight(20));
while (reader.Read())
{
Console.WriteLine("\t{0}|{1}",reader[0].ToString().PadRight(25),reader[1].ToString().PadRight(20));
}
}
catch (SqlException ex)
{
Console.WriteLine("Error:{0}", ex.Message);
}
finally
{
} Console.ReadLine();
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Server=zhuobin;uid=sa;pwd=zhuobin;database=northwind");
string sql = @"select contactname from customers";
try
{
conn.Open();
//create the command
SqlCommand cmd = new SqlCommand(sql,conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0}",reader[0]);
} reader.Close();
}
catch (SqlException ex)
{
Console.WriteLine("The error:" + ex.Message);
}
finally
{
conn.Close();
Console.WriteLine("The end!");
}
Console.ReadLine();
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Server=zhuobin;uid=sa;pwd=zhuobin;database=northwind");
string sql = @"select contactname from customers";
try
{
conn.Open();
//create the command
SqlCommand cmd = new SqlCommand(sql,conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0}",reader[0]);
} reader.Close();
}
catch (SqlException ex)
{
Console.WriteLine("The error:" + ex.Message);
}
finally
{
conn.Close();
Console.WriteLine("The end!");
}
Console.ReadLine();
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Test");
string fname = "zhuobin";
string lname = "bin";
SqlParameter firstName;
SqlParameter lastName;
SqlConnection conn = new SqlConnection("Data source=zhuobin;uid=sa;pwd=zhuobin;database=northwind");
string sqlqry = @"select count(*) from employees";
string sqlInsert = @"insert into employees(firstname,lastname)values(@fname,@lname)";
string sqldel = @"delete from employees where firstname=@fname and lastname=@lname";
SqlCommand cmdQry = new SqlCommand(sqlqry,conn);
SqlCommand cmdNon = new SqlCommand(sqlInsert,conn);
try
{
conn.Open();
Console.WriteLine("Before insert the number of tthe employees is {0}",cmdQry.ExecuteScalar());
firstName = new SqlParameter();
firstName.ParameterName = "@fname";
firstName.SqlDbType = SqlDbType.VarChar;
firstName.Size = 10;
firstName.Value = fname;
lastName = new SqlParameter();
lastName.ParameterName = "@lname";
lastName.SqlDbType = SqlDbType.VarChar;
lastName.Size = 10;
lastName.Value = lname;
cmdNon.Parameters.Add(firstName);
cmdNon.Parameters.Add(lastName);
// cmdNon.Parameters["fname"].Value = fname;
// cmdNon.Parameters["lname"].Value = lname;
Console.WriteLine("Execute statement:{0}",cmdNon.CommandText);
cmdNon.ExecuteNonQuery();
Console.WriteLine("After the insert the number of the employees is {0}",cmdQry.ExecuteScalar().ToString());
cmdNon.CommandText=sqldel;
Console.WriteLine("execute statement :{0}",cmdNon.CommandText);
cmdNon.ExecuteNonQuery();
Console.WriteLine("After the delete ,the number of the employees is {0}",cmdQry.ExecuteScalar().ToString());
}
catch (SqlException ex)
{
Console.WriteLine("Error:" + ex.Message);
}
finally
{
conn.Close();
}
Console.ReadLine();
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection(@"Data source=s013;Database=Northwind;integrated security=true");
//define the query string
string sqlqry = @"select count(*) from employees";
//define the insert into string
string sqlins = @"insert into employees(firstname,lastname)values('zhuo','bin')";
//define the delete string
string sqldel = @"delete from employees where firstname='zhuo' an lastname'bin'";
//
SqlCommand cmdQry = new SqlCommand(sqlqry,conn);
SqlCommand cmdIns = new SqlCommand(sqlins,conn);
try
{
conn.Open();
Console.WriteLine("Before insert ,the number of the employees {0}\n",cmdQry.ExecuteScalar().ToString());
Console.WriteLine("Execute Statement: {0}",cmdIns.CommandText);
cmdIns.ExecuteNonQuery();
Console.WriteLine("After insert ,the number of the employees is {0}",cmdQry.ExecuteScalar().ToString());
cmdIns.CommandText = sqldel;
cmdIns.ExecuteNonQuery();
Console.WriteLine("Execute Statement: {0}", cmdIns.CommandText);
Console.WriteLine("After delete :{0}",cmdQry.ExecuteScalar().ToString());
}
catch (SqlException ex)
{
Console.WriteLine("The error is :" + ex.Message);
}
finally
{
conn.Close();
}
Console.ReadLine();
}
}
}
SqlDataReader有Reader和GetValue()方法,前者是提取一行,后者是取行中某一列的值!
eg:
SqlDataReader rdr=cmd.ExecuteReader();
//
Table Northwind.Employees:
While(rdr.Read())
{
Console.WriteLine("Employee name:{0}{1}",rdr.GetValue(0),rdr.GetValue(1));
}
 Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string connString = @"Data Source=s013;database=northwind;integrated security=true";
SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();
Console.WriteLine("Connection opened!");
Console.WriteLine("Connection properties:");
Console.WriteLine("\tConnection String:{0}", conn.ConnectionString);
Console.WriteLine("\tDataBase:{0}", conn.Database);
Console.WriteLine("\tDataSource{0}:",conn.DataSource);
Console.WriteLine("\tServerVersion{0}",conn.ServerVersion);
Console.WriteLine("\tState:",conn.State.ToString());
Console.WriteLine("\tWorkStationId:",conn.WorkstationId.ToString());
}
catch (SqlException ex)
{
Console.WriteLine("Error:" + ex.Message);
}
finally
{
conn.Close();
Console.WriteLine("Connection Closed!");
}
Console.ReadLine();
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string connString = @"Data Source=s013;database=northwind;integrated security=true";
SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();
Console.WriteLine("Connection opened!");
Console.WriteLine("Connection properties:");
Console.WriteLine("\tConnection String:{0}", conn.ConnectionString);
Console.WriteLine("\tDataBase:{0}", conn.Database);
Console.WriteLine("\tDataSource{0}:",conn.DataSource);
Console.WriteLine("\tServerVersion{0}",conn.ServerVersion);
Console.WriteLine("\tState:",conn.State.ToString());
Console.WriteLine("\tWorkStationId:",conn.WorkstationId.ToString());
}
catch (SqlException ex)
{
Console.WriteLine("Error:" + ex.Message);
}
finally
{
conn.Close();
Console.WriteLine("Connection Closed!");
}
Console.ReadLine();
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string connString = @"Data Source=S013;Initial Catalog=Northwind;Integrated Security=True";
string sql = @"select * from employees";
SqlConnection conn = null;
SqlDataReader reader=null;
try
{
conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql,conn);
reader = cmd.ExecuteReader();
Console.WriteLine("This program demonstrrates the use of the SQL Server Data Provider.");
Console.WriteLine("Querying database {0} with query {1}\n",conn.Database,cmd.CommandText);
Console.WriteLine("First name\tLastName\n");
while (reader.Read())
{
Console.WriteLine("{0}|{1}",reader["firstname"].ToString().PadLeft(10),reader[1].ToString().PadLeft(10));
}
}
catch (SqlException ex)
{
Console.WriteLine("Error:"+ex);
}
finally
{
reader.Close();
conn.Close();
}
}
}
}
 Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string connString = @"Data Source=S013;Initial Catalog=Northwind;Integrated Security=True";
string sql = @"select * from employees";
SqlConnection conn = null;
SqlDataReader reader=null;
try
{
conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql,conn);
reader = cmd.ExecuteReader();
Console.WriteLine("This program demonstrrates the use of the SQL Server Data Provider.");
Console.WriteLine("Querying database {0} with query {1}\n",conn.Database,cmd.CommandText);
Console.WriteLine("First name\tLastName\n");
while (reader.Read())
{
Console.WriteLine("{0}|{1}",reader["firstname"].ToString().PadLeft(10),reader[1].ToString().PadLeft(10));
}
}
catch (SqlException ex)
{
Console.WriteLine("Error:"+ex);
}
finally
{
reader.Close();
conn.Close();
}
}
}
}
|