简体   繁体   中英

connecting to SQL Server from c#

i am reposting this question because alot of people here advised me to repost the error messages and the code for the DB_connection,the error is popping in the DB_Access class on this code conn = DB_conection.GetConnection()`;,i am working on a simple database project in c sharp and ms sql sever 2008 but im having an error upon compiling the program its poping up this message below

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:

and this my DB_connection class

 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;

        }

    }

and this is my code for the 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();

        }
    }
}

You have a NullReferenceException in the static constructor of your DB_conection [sic] class. The only possible place I can spot where that happens is in this line (line-breaks added for readability):

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

In particular, it looks as if the ConnnectionStrings[string] indexer property returns null . Typically it does that, when the connection string as specified by the name (here ConString ) cannot be found.

Make sure your application configuration file (named app.config in Visual Studio) contains a definition for the connection string named "ConString" in the connectionStrings element.

Example:

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

Of course, you would have to replace the "..." with the actual connection string .

Note that you have a couple of other issues in your code, like imminent SQL Injection , missing Dispose calls (or using blocks) on at least the SqlCommand objects, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM