从c#连接到SQL Server

时间:2012-09-17 11:07:53

标签: c# sql-server exception-handling

我正在重新发布这个问题,因为很多人建议我重新发布错误消息和DB_connection的代码,错误是在DB_Access类中弹出此代码conn = DB_conection.GetConnection()`;我是在c sharp和ms sql sever 2008中处理一个简单的数据库项目,但是在编译程序时出现错误,它弹出下面这条消息

System.TypeInitializationException was unhandled

  Message=The type initializer for 'StudentsInformationSystem.DB_conection' threw an exception.
  Source=StudentsInformationSystem
  TypeName=StudentsInformationSystem.DB_conection
  StackTrace:
       at StudentsInformationSystem.DB_conection.GetConnection()
       at StudentsInformationSystem.DB_Access..ctor() in C:\Users\soft\Documents\Visual Studio 2010\Projects\StudentsInformationSystem\StudentsInformationSystem\DB_Access.cs:line 16
       at StudentsInformationSystem.frmNewStudent..ctor() in C:\Users\soft\Documents\Visual Studio 2010\Projects\StudentsInformationSystem\StudentsInformationSystem\frmNewStudent.cs:line 14
       at StudentsInformationSystem.Form1.btnAddNewStudent_Click(Object sender, EventArgs e) in C:\Users\soft\Documents\Visual Studio 2010\Projects\StudentsInformationSystem\StudentsInformationSystem\Form1.cs:line 31
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at StudentsInformationSystem.Program.Main() in C:\Users\soft\Documents\Visual Studio 2010\Projects\StudentsInformationSystem\StudentsInformationSystem\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.NullReferenceException
       Message=Object reference not set to an instance of an object.
       Source=StudentsInformationSystem
       StackTrace:
            at StudentsInformationSystem.DB_conection..cctor() in C:\Users\soft\Documents\Visual Studio 2010\Projects\StudentsInformationSystem\StudentsInformationSystem\DB_conection.cs:line 15
       InnerException:

这是我的DB_connection类

 class DB_conection
    {
        public static SqlConnection NewCon;
        public static string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

        public static SqlConnection GetConnection() {

            NewCon = new SqlConnection(constr);
            return NewCon;

        }

    }

这是我的DB_Access代码

namespace StudentsInformationSystem
{
    class DB_Access
    {
        SqlConnection conn;
        public DB_Access() {

            conn = DB_conection.GetConnection();

        }
        public void add_student(string regNo,string fname, string lname, string phoneNo){

            if (conn.State == ConnectionState.Closed) {

                conn.Open();
            }
            SqlCommand newCmd = conn.CreateCommand();
            newCmd.Connection = conn;
            newCmd.CommandType = CommandType.Text;
            newCmd.CommandText = "insert into student values('" + regNo + "','" + fname + "','" + lname + "','" + phoneNo + "')";
            newCmd.ExecuteNonQuery();

        }
    }
}

1 个答案:

答案 0 :(得分:3)

NullReferenceException [sic]类的静态构造函数中有DB_conection。唯一可能发现的地方是这一行(为了便于阅读而增加了换行符):

public static string constr = 
    ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

特别是,ConnnectionStrings[string]索引器属性看起来好像返回null。通常情况下,当找不到名称(此处为ConString)指定的连接字符串时,就会这样做。

确保您的应用程序配置文件(在Visual Studio中名为app.config)包含connectionStrings元素中名为“ConString”的连接字符串的定义。

示例:

<connectionStrings>
  <add name="ConString" connectionString="..."/>
</connectionStrings>

当然,您必须将“...”替换为实际的connection string

请注意,您的代码中还有其他一些问题,例如即将发生的SQL Injection,至少DisposeusingSqlCommand个调用等等。