连接数据库示例
来源:互联网 发布:合肥程序员平均工资 编辑:程序博客网 时间:2024/06/06 01:19
using System;
using System.Data;
using System.Data.SqlClient;
namespace Microsoft.AdoNet.DataSetDemo
{
class NorthwindDataSet
{
static void Main()
{
string connectionString = GetConnectionString();
ConnectToData(connectionString);
}
private static void ConnectToData(string connectionString)
{
//Create a SqlConnection to the Northwind database.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
//Create a SqlDataAdapter for the Suppliers table.
SqlDataAdapter adapter = new SqlDataAdapter();
// A table mapping names the DataTable.
adapter.TableMappings.Add("Table", "Suppliers");
// Open the connection.
connection.Open();
Console.WriteLine("The SqlConnection is open.");
// Create a SqlCommand to retrieve Suppliers data.
SqlCommand command = new SqlCommand(
"SELECT SupplierID, CompanyName FROM dbo.Suppliers;",
connection);
command.CommandType = CommandType.Text;
// Set the SqlDataAdapter's SelectCommand.
adapter.SelectCommand = command;
// Fill the DataSet.
DataSet dataSet = new DataSet("Suppliers");
adapter.Fill(dataSet);
// Create a second Adapter and Command to get
// the Products table, a child table of Suppliers.
SqlDataAdapter productsAdapter = new SqlDataAdapter();
productsAdapter.TableMappings.Add("Table", "Products");
SqlCommand productsCommand = new SqlCommand(
"SELECT ProductID, SupplierID FROM dbo.Products;",
connection);
productsAdapter.SelectCommand = productsCommand;
// Fill the DataSet.
productsAdapter.Fill(dataSet);
// Close the connection.
connection.Close();
Console.WriteLine("The SqlConnection is closed.");
// Create a DataRelation to link the two tables
// based on the SupplierID.
DataColumn parentColumn =
dataSet.Tables["Suppliers"].Columns["SupplierID"];
DataColumn childColumn =
dataSet.Tables["Products"].Columns["SupplierID"];
DataRelation relation =
new System.Data.DataRelation("SuppliersProducts",
parentColumn, childColumn);
dataSet.Relations.Add(relation);
Console.WriteLine(
"The {0} DataRelation has been created.",
relation.RelationName);
}
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=SSPI";
}
}
}
- asp连接数据库示例
- asp连接数据库示例
- asp连接数据库示例
- 连接数据库示例
- JSP连接数据库示例
- jdbc连接数据库示例
- Java连接数据库示例
- 连接mysql数据库示例
- Java连接数据库的示例
- ASP连接数据库语句示例
- Java连接Excel数据库示例
- java 连接access数据库示例
- Java连接Excel数据库示例
- C#连接Oracle数据库示例
- Java连接Oracle数据库示例
- MySql连接数据库简单示例
- 连接Oracle数据库示例代码
- JDBC连接MYSQL数据库示例
- JS中的instanceof和typeof
- Jquery 乱码问题
- IIS的安装和配置全过程
- Android中定时器的3种实现方法
- levelDB源码分析-SSTable:.sst文件构建与读取
- 连接数据库示例
- 修改struts2的.action后缀名
- levelDB源码分析-TableCache
- Grindr:日活跃用户达100万的基友月抛应用
- 写BOKE有积分吗?
- 理解inode
- 进程的内核对象句柄表
- 正则表达式---小节(一)
- [转载]Flex开源项目