您的位置:首页 > 其它

连接数据庫各种对象的使用

2008-05-09 12:36 375 查看
SqlConnection对象的使用
用SqlConnection连接到SQL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间,使能够访问这些命名空间的类
using System.Data.SqlClient;

namespace SQLServerProvider
{
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection();//创建SqlConnection对象(末初始化,需要指明属性)
//连接字符串包含三个子句,服务器,安全,和超时。可以在连接字符串内使用的子句(数据源)包括:
//服务器名称(笔者的是CCF-AB6AF50C243,计算机名),实例名称,服务器地址。Server=localhost指明连接到SQL Server实例名称,local代表SQL Server与客户程序位于相同机器上。
//如果通过TCP/IP网络访问SQL Server,可以指出服务器的IP地址,Server=192.168.1.10。
//SSPI代表Security Support Provider Interface,便可以使用当前Windows登录信息登录到SQL Server数据庫,用True代替SSPI也可以。
thisConnection.ConnectionString =
"Server=(local)//CCF-AB6AF50C243;user id=sa;password=;Connection Timeout=5;";
try
{
thisConnection.Open();
Console.WriteLine("Connection Succefully closed!");
thisConnection.Close();
}
catch (SqlException ex)
{
Console.WriteLine("{0}", ex.ToString());
}

}
}
}

用OleDbConnec tion连接到Microsoft Access:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间,使能够访问这些命名空间的类
using System.Data.OleDb;

namespace SQLServerProvider
{
class Program
{
static void Main(string[] args)
{
OleDbConnection thisConnection = new OleDbConnection();//创建OleDbConnection对象(末初始化,需要指明属性)
//连接字符串包含三个子句,服务器,安全,和超时。可以在连接字符串内使用的子句(数据源)包括:
//服务器名称,实例名称,服务器地址。Server=localhost指明连接到SQL Server实例名称,local代表SQL Server与客户程序位于相同机器上。
//如果通过TCP/IP网络访问SQL Server,可以指出服务器的IP地址,Server=192.168.1.10。
//连接字符串与SqlConnection不同的是,必须指定连接到OLE DB提供者,对于Microsoft Access数据// //庫,OLE DB提供者始终使用下面的名称("Jet"是包含在Access中的数据庫引擎的名称);

thisConnection.ConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/MyProject/CSharpDatabase/db1.mdb;";
try
{
thisConnection.Open();
Console.WriteLine("Connection Succefully closed!");

thisConnection.Close();
}
catch (OleDbException ex)
{
Console.WriteLine("{0}", ex.ToString());
}

}
}
}

Command对象的使用
创建Command对象

//可以用SqlCommand构造函数或者使用为我们创建对象的方法创建Command对象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间,使能够访问这些命名空间的类
using System.Data.SqlClient;

namespace SQLServerProvider
{
class Program
{

static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection();//创建SqlConnection对象
thisConnection.ConnectionString =
"Server=localhost;Integrated Security=SSPI;Connection TimeOut=5";
SqlCommand thisCommand = new SqlCommand();//创建SqlCommand对象
thisCommand.CommandText = "SELECT COUNT(*) FROM Employees";//设置文件属性
Console.WriteLine("Command object created.");
Console.WriteLine("Ready to execute SQL command:{0}",thisCommand.CommandText);
try
{
thisConnection.Open();
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
thisConnection.Close();
Console.WriteLine("Connection closed");
}
}
}
}

关联命令与连接

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间,使能够访问这些命名空间的类
using System.Data.SqlClient;

namespace SQLServerProvider
{
class Program
{

static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection();//创建SqlConnection对象
thisConnection.ConnectionString =
"Server=localhost;Integrated Security=SSPI;Database=Northwind;Connection TimeOut=5";
SqlCommand thisCommand = new SqlCommand();//创建SqlCommand对象

try
{
thisConnection.Open();
//把Connection对象分配给Command对象的Connection属性,将这两个对象关联起来
thisCommand.Connection = thisConnection;
//等价的写法
// SqlCommand thisCommand=thisConnection.CreateCommand();
Console.WriteLine("Create Command Object on this connection.");
// 返回一个结果的命令ExecuteScalar
int count = (int)thisCommand.ExecuteScalar();//返回类型为object,要强制转换
Console.WriteLine("Number of Employees is:{0}", count);
//返回多个结果的命令ExecuteReader()方法
     SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
Console.WriteLine("Employee name:{0}{1}",
thisReader.GetValue(0),
thisReader.GetValue(1));
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
thisConnection.Close();
Console.WriteLine("Connection closed");
}
}
}
}
为了减少代码,可以这样子写:
SqlCommand thisCommand=new SqlCommand("SELECT COUNT(*) FROM Employees",thisConnection);
Command对象提供了几个不同的方法,用于执行SQL命令。
ExecuteNoneQuery 不返回任何结果:语句不是查询
ExecuteScalar   单个值
ExcuteReader   一个或多个行
ExcuteXmlReader XML

执行非查询命令
ExecuteNonQuery方法:
1.添加,删除记录
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间,使能够访问这些命名空间的类
using System.Data.SqlClient;

namespace SQLServerProvider
{
class Program
{

static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection();//创建SqlConnection对象
thisConnection.ConnectionString =
"Server=localhost;Integrated Security=SSPI;Connection TimeOut=5;Database=Northwind";

//创建Command对象,对表中的数据行计数
SqlCommand selectCmd = new SqlCommand("SELECT COUNT(*) FROM Employees", thisConnection);
//创建Command对象,用于INSERT和DELETE
SqlCommand nonQueryCmd = thisConnection.CreateCommand();

try
{
thisConnection.Open();
//插入之前的行数
Console.WriteLine("Before INSERT:Number of Employees is:{0}", selectCmd.ExecuteScalar());

//设置INSERT文本属性
nonQueryCmd.CommandText = "INSERT INTO Employees(FirstName,LastName) values('Steven','Jin')";
Console.WriteLine(nonQueryCmd.CommandText);
//执行ExecuteNonQuery,插入记录
Console.WriteLine("Number of Rows Affected is:{0}",nonQueryCmd.ExecuteNonQuery());
Console.WriteLine("After INSERT:Number of Employees is:{0}", selectCmd.ExecuteScalar());

//设置DELETE文本属性
nonQueryCmd.CommandText = "DELETE FROM Employees WHERE FirstName='Steven' AND LastName='Jin'";
Console.WriteLine(nonQueryCmd.CommandText);
//执行ExecuteNonQuery删除记录
Console.WriteLine("Number of Rows Affected is:{0}", nonQueryCmd.ExecuteNonQuery());
Console.WriteLine("After DELETE:Number of Employees is:{0}",selectCmd.ExecuteScalar());
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
thisConnection.Close();
Console.WriteLine("Connection closed");
}
}
}
}

2.创建表单:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间,使能够访问这些命名空间的类
using System.Data.SqlClient;

namespace SQLServerProvider
{
class Program
{

static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection();//创建SqlConnection对象
thisConnection.ConnectionString =
"Server=localhost;Integrated Security=SSPI;Connection TimeOut=5;Database=mydatabase";

//创建Command对象,对表中的数据行计数
SqlCommand selectCmd = new SqlCommand("SELECT COUNT(*) FROM mytable", thisConnection);
//创建Command对象,用于INSERT和DELETE
SqlCommand nonQueryCmd = thisConnection.CreateCommand();

try
{
//执行non-query创建一个临时表
thisConnection.Open();
nonQueryCmd.CommandText = "CREATE TABLE mytable(COL1 integer)";
nonQueryCmd.ExecuteNonQuery();

//执行non-query插入一些数据
nonQueryCmd.CommandText="INSERT INTO mytable(COL1) VALUES('20')";
Console.WriteLine("Number of Rows Affected is:{0}", nonQueryCmd.ExecuteNonQuery());

}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
thisConnection.Close();
Console.WriteLine("Connection closed");
}
}
}
}

3.创建数据庫

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间,使能够访问这些命名空间的类
using System.Data.SqlClient;

namespace SQLServerProvider
{
class Program
{

static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection();//创建SqlConnection对象
thisConnection.ConnectionString =
"Server=localhost;Integrated Security=SSPI;Connection TimeOut=5;Database=mydatabase";

//创建Command对象,对表中的数据行计数
SqlCommand selectCmd = new SqlCommand("SELECT COUNT(*) FROM mytable", thisConnection);
//创建Command对象,用于INSERT和DELETE
SqlCommand nonQueryCmd = thisConnection.CreateCommand();

try
{
thisConnection.Open();
//执行non-query创建一个数据庫
nonQueryCmd.CommandText = "CREATE DATABASE DATABASETEMP";
nonQueryCmd.ExecuteNonQuery();
//切换到新创建的数据庫
thisConnection.ChangeDatabase("DATABASETEMP");

//创建一个新的表单 
nonQueryCmd.CommandText = "CREATE TABLE temptable(COL1 int)";
nonQueryCmd.ExecuteNonQuery();

//执行non-query插入一些数据
nonQueryCmd.CommandText = "INSERT INTO temptable(COL1) VALUES('20')";
Console.WriteLine("Number of Rows Affected is:{0}", nonQueryCmd.ExecuteNonQuery());

}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
thisConnection.Close();
Console.WriteLine("Connection closed");
}
}
}
}
使用命令参数

using System;
SQL命令的参数在命令文本中是占位符(有些使用末指定参数?),标记出将被替代的值的位置。SQL Server中指定参数,这些参数以@符号开始,后跟不带空格的名称。在下面的INSERT语句中,@MyName和@MyNumber都是参数:INSERT INTO MyTable VALUES(@MyName,@MyNumber);
下面的例子中,首先在INSERT命令的文本内指定名为@MyName和@MyNumber的参数:
nonQueryCmd.CommandText = "INSERT INTO MyTable VALUES(@MyName,@MyNumber)";
接下来,给sqlCommand对象的Parameters集合添加这些参数,这里使用该集合的Add方法给集合添加新成员:
nonQueryCmd.Parameters.Add("@MyName", SqlDbType.VarChar, 30);
nonQueryCmd.Parameters.Add("@MyNameNumber", SqlDbType.Int);
SqlDbType名称必须与命令中使用的名称匹配。建立参数只不过就是根据需要插入不同的数据值。数组中有四个名称,所以,name[0]是"Enrio",name[1]是"Franco",依次类推。执行for循环,把@MyName参数设置为来自names[]数组的名称,把@MyNumber参数设置为用来每次遍历for 的整数索引。通过对参数的Value属性赋值,告诉系统把程序变量的值转换为适当的文本,以替换到INSERT命令中。
参数替代不改变命令文本字符串,相反,在服务器上执行命令时才替代参数。
因此,对于循环的每次迭代,语句Console.WriteLine(nonQueryCmd.CommandText)显示的是:
INSERT INTO MyNameTable VALUES(@MyName,@MyNameNumber
实际执行命令时,服务器在第1次迭代中用"Enrico"替代@MyName,用0替代MyNumber;
在第2次迭代中用"Frances"替代@MyName,用1替代@MyNumber,依此类推。每次执行命令,都有1个行受到影响。结果与我们执行了文字命令一样:
INSERT INTO MyTable VALUES("Enrico",0)
......

using System.Collections.Generic;
using System.Linq;
using System.Text;
//导入命名空间,使能够访问这些命名空间的类
using System.Data.SqlClient;
using System.Data;
namespace SQLServerProvider
{
class Program
{

static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection();
thisConnection.ConnectionString =
"Server=localhost;Integrated Security=SSPI;Connection TimeOut=5;Database=mydatabase";

SqlCommand nonQueryCmd = thisConnection.CreateCommand();

try
{
thisConnection.Open();

nonQueryCmd.CommandText = "CREATE TABLE MyTable(MyName VARCHAR(30),MyNumber integer)";
Console.WriteLine(nonQueryCmd.CommandText);
nonQueryCmd.ExecuteNonQuery();
nonQueryCmd.CommandText = "INSERT INTO MyTable VALUES(@MyName,@MyNumber)";

nonQueryCmd.Parameters.Add("@MyName", SqlDbType.VarChar, 30);
nonQueryCmd.Parameters.Add("@MyNumber", SqlDbType.Int);

nonQueryCmd.Prepare();

string[] names = { "Enrico", "Franco", "Gloria", "Horace" };
int i;
for (i = 1; i <= 4; i++)
{
nonQueryCmd.Parameters["@MyName"].Value = names[i - 1];
nonQueryCmd.Parameters["@MyNumber"].Value = i;
Console.WriteLine(nonQueryCmd.CommandText);
Console.WriteLine("Number of Rows Affected is:{0}", nonQueryCmd.ExecuteNonQuery());

}
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
thisConnection.Close();
Console.WriteLine("Connection closed");
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐