一点点的不注意就不能成功。在web.config 里面写的连接数据库有两种,一种在<connectionStrings/>里面写,现在采用的比较多,另一种是在<appSettings/ >里写,都能实现,但是不同的连接方法也有细微的差别。今天一天不在状态,磨磨蹭蹭终于修改成功才把这个程序写成功,现在和大家分享一下,希望大家多多指教。
1.在web.config里面写如下。
<appSettings >
<add key="SQLConnectionString" value="Provider=sqloledb;data source=../SQLEXPRESS;initial catalog=Database1;User ID= sa;Password=xxxx ;persist security info=False;" />
</appSettings>
2.在对应页面的.cs文件里这样写,本例是利用
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
.......
//把文件导入到数据库
//string conn = ConfigurationSettings.AppSettings["SQLConnectionString"]; 已经过时所以用下面这句
string strconn = System.Configuration.ConfigurationManager.AppSettings["SQLConnectionString"];
OleDbConnection myConnection = new OleDbConnection(strconn); //一开始有问题,提示没有Provider=sqloledb;
string strSql1 = " if exists(select * from sysobjects where id = object_id('TempImportData1')) drop table TempImportData1 ";
string strSql2 = " select * into TempImportData1 from opendatasource( 'Microsoft.Jet.OLEDB.4.0','Data Source=/"" + strFilePathAll + "/";User ID=Admin;Password=;Extended properties=Excel 8.0')...[Sheet1$] ";
try
{
OleDbCommand comm1 = new OleDbCommand(strSql1, myConnection);
OleDbCommand comm2 = new OleDbCommand(strSql2, myConnection);
myConnection.Open();
comm1.ExecuteNonQuery();
comm2.ExecuteNonQuery();
myConnection.Close();
}
catch(OleDbException ex)
{
// Console.WriteLine("--------NO------------");
Response.Write(ex.Message );
}
finally
{
myConnection.Close();//自居都会确保强制关闭数据连接。
}
..............
总结:本人一开始怎么也没法把它连接,但是最终发现问题出现在没有Provider=sqloledb;其实在<connectionStrings/>配置时大都是这样写的
<connectionStrings>
<add name="MyTestConnectionString" connectionString="Data Source=OPEN-EQIANG/SQLEXPRESS;Initial Catalog=WebSiteTest;User ID=sa;Password=qwertyuiop;Persist Security Info=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
这样里面是由providerName的配置的。总算有了一点点的收获,也不一定最好,但是总算憋出来了。呵呵