ユーザーがボタンをクリックすると、テキストボックスの指定された名前がSQLデータベースのテーブルに追加されるような、テキストボックスとボタンが付いたフォームがあります。SQL構文エラー(INSERTコマンド)
private void btnAddDiaryItem_Click(object sender, EventArgs e)
{
try
{
string strNewDiaryItem = txtAddDiaryItem.Text;
if (strNewDiaryItem.Length == 0)
{
MessageBox.Show("You have not specified the name of a new Diary Item");
return;
}
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES = ('" + strNewDiaryItem + "');";
cSqlQuery cS = new cSqlQuery(sqlText, "non query");
PopulateInitialDiaryItems();
MessageBox.Show("New Diary Item added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Unhandled Error: " + ex.Message);
}
}
クラスcSqlQueryが私のために、様々なT-SQLのアクションを実行する単純なクラスであり、そのコードは次のとおりです。:
はclass cSqlQuery
{
public string cSqlStat;
public DataTable cQueryResults;
public int cScalarResult;
public cSqlQuery()
{
this.cSqlStat = "empty";
}
public cSqlQuery(string paramSqlStat, string paramMode)
{
this.cSqlStat = paramSqlStat;
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
if (paramMode == "non query")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
sqlCom.ExecuteNonQuery();
linkToDB.Close();
}
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(cSqlStat, linkToDB))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
this.cScalarResult = (Int32)sqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public cSqlQuery(SqlCommand paramSqlCom, string paramMode)
{
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
paramSqlCom.Connection = linkToDB;
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(paramSqlCom))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
paramSqlCom.Connection = linkToDB;
this.cScalarResult = (Int32)paramSqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public string BuildConnectionString()
{
cConnectionString cCS = new cConnectionString();
return cCS.strConnect;
}
}
クラスがうまく機能し、次のようにボタンのコードです私のアプリケーション全体を通してエラーがクラスにあるとは思わないが、私は確信が持てません。
私はボタンをクリックすると、私は、次のエラーメッセージが表示されます。
不適切な構文は近く、私は、SQL Management Studioでまったく同じコマンドを実行したときので、私は本当に迷惑です
を=それはうまく動作します。
かなりシンプルなものがありませんが、コードを何度も読んだ後で、どこが間違っているのか分かりません。
は、パラメータ化クエリを調べてください。非正規化されたユーザー入力でデータベースに移動しないでください。 –
「MyDiaryItem」という形式でこれを入力してください。 DROP TABLE tblDiaryTypes'。次に、このGoogle検索のリンクのいくつかを読んでください:http://www.google.com/search?q=sql+injection – jeroenh