私はC#とSQLが初めてです単純な学生データベースを作成しています.SQL Server 2008で作成したデータベースを追加しました.今、入力が与えられるフォームがあり、データをデータベースに挿入するためのボタン挿入があります. しかし、ボタンをクリックすると例外が発生します。
これは私の App.config ファイルです
`<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<configSections>
<connectionStrings>
<appSettings>
<add name="ConString" connectionString="Data Source=ARAVIND-HP\SQLEXPRESS; Initial Catalog=test;Integrated Security=True" providerName="System.Data.sqlClient"/>
</appSettings>
</connectionStrings>
`
私が使用したフォームを以下に示します
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class frmNewStudent : Form
{
public frmNewStudent()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void frmNewStudent_Load(object sender, EventArgs e)
{
}
private void btnInsert_Click(object sender, EventArgs e)
{
DB_Access access = new DB_Access();
access.add_student(txtRegNo.Text,txtFName.Text,txtLName.Text,txtPhone.Text);
MessageBox.Show("Data added successfully");
}
}
}
今、私は2つのクラス1.DB_access 2.DB_Connectionsを持っています
DB_accessのコードは以下です
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace test
{
class DB_Access
{
public SqlConnection conn;
public DB_Access()
{
conn = DB_Connection.GetConnection();
}
public void add_student(string regno, string fname, string lname, string phone)
{
if(conn.State.ToString()=="Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "insert into student values('"+ regno +"','"+ fname +"','"+ lname +"','"+ phone +"')";
newCmd.ExecuteNonQuery();
}
}
}
DB_Connections のコードは以下のとおりです
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace test
{
class DB_Connection
{
public static SqlConnection NewCon;
public static string ConStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public static SqlConnection GetConnection()
{
NewCon = new SqlConnection(ConStr);
return NewCon;
}
}
}
これを実行して挿入ボタンをクリックすると、次の例外が発生します。
test.exe で 'System.TypeInitializationException' 型の未処理の例外が発生しました
追加情報: 「test.DB_Connection」の型初期化子が例外をスローしました。
および行「conn = DB_Connection.GetConnection();」ハイライトされる
私はエラーを見つけることができません.これで私を助けてください