总是报:用户未定义sqlexcption!网上说是connectstring 有问题,可我对比了下,连接数据库的字符串一样的,求大神教教我完整的C#连接SQL server的方法和要点,包括web.config的配置等,感激不尽。急求,新手调试C#项目很难受啊!
```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"/>
-->
截图看一下,不能不知道什么错
大兄弟,就是这么错的,你跟我说下C#一般怎么连接数据库的
检查你的实例名是否正确,改用ip或助记名试试,查看网络是否正常
SqlConnection con = new SqlConnection("server=xxx\\xxxx;database=db_xx;uid=aaa;pwd=bbb;");
试试修改这句话,server设置为你的计算机名称或者ip,给sa设置一个密码
https://support.microsoft.com/zh-cn/kb/914277
sa用户权限设置完 即可
//连接字符串
SqlConnection conn = new SqlConnection("server=.;database=DByuekao;uid=sa;pwd=123456;");
//打开连接
conn.Open();
//适配器对象
SqlDataAdapter sda = new SqlDataAdapter("select h.*,t.TName from House h,HouseType t where h.HouseTypeNo=t.HouseTypeNo", conn);
//数据集对象
DataSet ds = new DataSet();
//向数据及对象中填充数据
sda.Fill(ds);
//关闭连接
conn.Close();
//释放资源
conn.Dispose();
把cs文件发我,我看一下,还有错误信息
是我自己数据库设置问题,看别人代码的确耐心才能出结果。。。