在 asp.net 中出现“找不到类型或命名空间名称‘SqlConnection’(是否缺少 using 指令或程序集引用?)”错误,经检查,问题起因令人哭笑不得。
问题
C#程序代码如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace studentA
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- }
-
- protected void saveButton_Click(object sender, EventArgs e)
- {
-
- string name = nameTextBox.Text;
- string email = emailTextBox.Text;
- string phone = phoneTextBox.Text;
- string reg = regTextBox.Text;
-
- Student student = new Student(name, email, phone, reg);
-
-
- string connectionString = @"Server=.\SQLEXPRESS;Database=db;Integrated Security=true";
- SqlConnection connection = new SqlConnection(connectionString);
-
- string query = "INSERT INTO Students VALUES('" + student.Name + "','" + student.Email + "','" + student.Phone + "','" + student.Reg + "')";
-
- SqlCommand command = new SqlCommand(query, connection);
-
- connection.open();
- int rowAffected=command.ExecuteNonQuery();
- connection.close();
-
- if (rowAffected > 0)
- {
- messageLabel.Text = "success";
- }
- else
- {
- messageLabel.Text = "failed";
- }
- Response.Write(rowAffected);
-
- }
- }
- }
新窗显示代码
复制代码
分析
错误在 SqlConnection connection = new SqlConnection(connectionString); 那行,我正在使用 MSVS 2013 和 Microsoft sql server,我尝试添加 System.Data.SqlClient;。
当我添加 System.Data.SqlClient 命名空间时,它给出了另一个错误:
错误 1 'System.Data.SqlClient.SqlConnection' 不包含 'close' 的定义并且没有扩展方法 'close' 接受类型为 'System' 的第一个参数(您是否缺少 using 指令或程序集引用?)
解决
问题解决了!
编写代码 connection.open(); 和connection.close();的问题,用 connection.Close(); 代替connection.close();,用connection.Open(); 代替connection.open(); ,之前用小写字母,是不对的!
C#代码区分大小写字母,一个不经意的失误,导致了问题的产生。
相关文章