我将根据教程创建一个学生信息系统。一旦用户想要将新学生添加到数据库中,就会发生以下异常。
我试图学习一些关于 TypeInitializationException 的东西,我对它的名字有点了解..但我不能完全理解。此外,我正在关注的教程中没有异常。我是这种类型的 OOP 编程和处理错误的新手。我在下面包括了我的数据库连接和数据库访问类..
我的DB_Connection
班级
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace studentInformationSystem
{
class DB_Connection
{
public static SqlConnection NewConnection;
public static string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public static SqlConnection getConnection()
{
NewConnection = new SqlConnection(ConString);
return NewConnection;
}
}
}
我的DB_Access
班级
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace studentInformationSystem
{
class DB_Access
{
public SqlConnection conn;
public DB_Access()
{
conn = DB_Connection.getConnection();
}
public void AddStudent(string regNo, string fName, string lName, string phoneNumber)
{
if(conn.State.ToString() == "Closed")
{
conn.Open();
}
SqlCommand newCommand = conn.CreateCommand();
newCommand.Connection = conn; //why we use it..???
newCommand.CommandType = CommandType.Text;
newCommand.CommandText = "insert into student values('" + regNo + "','" + fName + "','" + lName + "','" + phoneNumber + "')";
newCommand.ExecuteNonQuery();
}
}
}
这是我的连接字符串
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<configSections>
<connectionStrings>
<add name="ConString" connectionString="Data Source=SADID-PC\SQLEXPRESS;Initial Catalog=Test1;Integrated Security=True"
providerName="System.Data.sqlClient" />
</connectionStrings>
</configSections>
</configuration>