あなたのクエリには多くの問題があります。
これはあなたのコードの修正版です
string connetionString = null;
string sql = null;
// All the info required to reach your db. See connectionstrings.com
connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// Prepare a proper parameterized query
sql = "insert into Main ([Firt Name], [Last Name]) values(@first,@last)";
// Create the connection (and be sure to dispose it at the end)
using(SqlConnection cnn = new SqlConnection(connetionString))
{
try
{
// Open the connection to the database.
// This is the first critical step in the process.
// If we cannot reach the db then we have connectivity problems
cnn.Open();
// Prepare the command to be executed on the db
using(SqlCommand cmd = new SqlCommand(sql, cnn))
{
// Create and set the parameters values
cmd.Parameters.Add("@first", SqlDbType.NVarChar).Value = textbox2.text;
cmd.Parameters.Add("@last", SqlDbType.NVarChar).Value = textbox3.text;
// Let's ask the db to execute the query
int rowsAdded = cmd.ExecuteNonQuery();
if(rowsAdded > 0)
MessageBox.Show ("Row inserted!!" + );
else
// Well this should never really happen
MessageBox.Show ("No row inserted");
}
}
catch(Exception ex)
{
// We should log the error somewhere,
// for this example let's just show a message
MessageBox.Show("ERROR:" + ex.Message);
}
}
- 列名にはスペースが含まれているため(これは避ける必要があります)、それらを角括弧で囲む必要があります
using
接続が閉じられ、リソースが解放されることを確認するには、ステートメントを使用する必要があります
- コントロールを文字列に直接配置しますが、これは機能しません
- 引用の問題や sqlinjiection 攻撃を避けるために、パラメータ化されたクエリを使用する必要があります
- 単純な挿入クエリに DataAdapter を使用する必要はありません
- バグの原因となる可能性があるため、AddWithValue は使用しないでください (以下のリンクを参照)。
これとは別に、他の潜在的な問題があります。ユーザーがテキスト ボックス コントロールに何も入力しない場合はどうなりますか? 挿入する前に、これについて何かチェックしましたか? 前述したように、フィールド名にはスペースが含まれているため、コードに不便が生じます。これらのフィールド名を変更してみてください。
このコードは、データベースの列が NVARCHAR 型であると想定しています。そうでない場合は、適切なSqlDbType 列挙値を使用します。
できるだけ早く、より新しいバージョンの NET Framework に切り替えることを計画してください。1.1 は本当に時代遅れです。
また、AddWithValue の問題については、この記事で避けるべき理由を説明します。AddWithValue() の使用をやめることはできますか?