总是报:用户未定义sqlexcption!网上说是connectstring 有问题,可我对比了下,连接数据库的字符串一样的,求大神教教我完整的C#连接SQL server的方法和要点,包括web.config的配置等,感激不尽。急求,新手调试C#项目很难受啊!
8条回答 默认 最新
- Zmyths 2016-08-25 03:16关注
```private string ExecuteScript(string SQLFile, string scriptName)
{
//TODO: Beef up error reporting code
string ErrorString = string.Empty;
SqlConnection conn = null;WriteText(HttpContext.Current.Response, "Installing Script " + scriptName); try { //Open the Schema File, read it and install it. using (StreamReader sr = new StreamReader(SQLFile)) { // Create new connection to database conn = new SqlConnection(_connectionString); conn.Open(); while (!sr.EndOfStream) { StringBuilder sb = new StringBuilder(); SqlCommand cmd = conn.CreateCommand(); while (!sr.EndOfStream) { string s = sr.ReadLine(); if (s != null && s.ToUpper().Trim().Equals("GO")) { break; } sb.AppendLine(s); } // Execute T-SQL against the target database cmd.CommandText = sb.ToString(); cmd.CommandTimeout = 600; cmd.ExecuteNonQuery(); } WriteText(HttpContext.Current.Response, " - Success<br>"); } } catch { WriteText(HttpContext.Current.Response, " - Error<br>"); ErrorString = "Error Installing Schema"; } finally { //Clos Out the Connection if (conn != null) { try { conn.Close(); conn.Dispose(); } catch (Exception e) { ErrorString = String.Format(@"Could not close the connection. Error was {0}", e.ToString()); } } } return ErrorString; } 下面是connectstring: <connectionStrings> <!-- SQL Server Native Client Connection String --> <add name="DotNetSCORMDB" connectionString="Data Source=(local);Initial Catalog=DotNetSCORM;Persist Security Info=True;User ID=sa;Password=123" providerName="System.Data.SqlClient" /> <!-- SQL Express Connection String - See readme.txt for setup instructions <add name="DotNetSCORMDB" connectionString="initial catalog=DotNetSCORM;Data Source=.\SQLExpress;Integrated Security=true;AttachDBFileName=|DataDirectory|Club.mdf;User Instance=True" providerName="System.Data.SqlClient"/> -->
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报