[英]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 我正在重新发布此问题,因为很多人建议我重新发布错误消息和DB_connection的代码,该代码conn = DB_conection.GetConnection()`上的DB_Access类中弹出错误,我正在研究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:
and this my DB_connection class 这是我的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;
}
}
and this is my code for the DB_Access 这是我的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. DB_conection
[sic]类的静态构造函数中有一个NullReferenceException
。 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
. 特别是,看起来好像
ConnnectionStrings[string]
索引器属性返回null
。 Typically it does that, when the connection string as specified by the name (here ConString
) cannot be found. 当
ConString
由名称(此处为ConString
)指定的连接字符串时,通常ConString
。
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. 确保您的应用程序配置文件(在Visual Studio中名为
app.config
)在connectionStrings
元素中包含名为“ ConString”的连接字符串的定义。
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. 请注意,您的代码中还有其他一些问题,例如即将到来的SQL Injection ,至少在
SqlCommand
对象上缺少Dispose
调用(或using
块)等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.