日期:2014-05-16  浏览次数:20523 次

.Net通过Ole方式和SQL方式访问SqlServer数据库

Ole方式连接数据库写法:

?

<connectionStrings>
  <add connectionString="Data Source=LIFAN;DataBase=NorthWind;User ID=**;Password=**;Provider=SQLOLEDB" name="connectionString"/>
</connectionStrings>
?
using(OleDbConnection con=new OleDbConnection(conStr)){
String sql = "Select contactName,City,Country from Customers where contactName=?";
            OleDbCommand command = new OleDbCommand(sql, con);
            command.Parameters.Add("@Name", OleDbType.VarChar, 20);
            command.Parameters[0].Value = name;

            OleDbDataReader reader = command.ExecuteReader();
}

?

?Sql方式连接数据库写法:

?

    <connectionStrings>
        <add connectionString="Data Source=LIFAN;DataBase=NorthWind;User ID=**;Password=**" name="connectionString"/>
    </connectionStrings>
?
using(SqlConnection con=new SqlConnection(conStr)){
String sql = "Select contactName,City,Country from Customers where contactName=@Name";
            SqlCommand command = new SqlCommand(sql, con);
            command.Parameters.Add("@Name", SqlDbType.VarChar, 20);
            command.Parameters[0].Value = name;
            
            SqlDataReader reader = command.ExecuteReader();
}

?主要区别在:

Ole中的sql语句 :

Select contactName,City,Country from Customers where contactName=?

如果写成 :

Select contactName,City,Country from Customers where contactName=@Name

?会报:“必须声明标量变量 "@Name"错误”。

?

Sql中的sql语句:

Select contactName,City,Country from Customers where contactName=@Name