我想创建一个用于从类对象插入的SQL字符串。
示例
object data = { id = Textbox1.Text, name = Textbox2.Text };
我想从中创建:
insert into mytable(id, name) values (@id, @name)
和
update mytable set id = @id, name = @name
和
delete from mytable where id = @id
您可以使用任何想要的方法代替OdbcXXXX来尝试此操作:
using System.Data.Odbc;
private void ActionInsert_Click(object sender, EventArgs e)
{
var connection = new OdbcConnection(Properties.Settings.Default.ConnectionString);
connection.Open();
try
{
var cmdInsert = new OdbcCommand("insert into mytable (id, name) values (?,?)",
connection);
cmdInsert.Parameters.Add("@id", OdbcType.Text).Value = Textbox1.Text;
cmdInsert.Parameters.Add("@name", OdbcType.Text).Value = Textbox2.Text;
cmdInsert.ExecuteNonQuery();
}
catch ( Exception ex )
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
private void ActionUpdate_Click(object sender, EventArgs e)
{
var connection = new OdbcConnection(Properties.Settings.Default.ConnectionString);
connection.Open();
try
{
var cmdUpdate = new OdbcCommand("update mytable set id=?, name=?",
connection);
cmdUpdate.Parameters.Add("@id", OdbcType.Text).Value = Textbox1.Text;
cmdUpdate.Parameters.Add("@name", OdbcType.Text).Value = Textbox2.Text;
cmdUpdate.ExecuteNonQuery();
}
catch ( Exception ex )
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
private void ActionDelete_Click(object sender, EventArgs e)
{
var connection = new OdbcConnection(Properties.Settings.Default.ConnectionString);
connection.Open();
try
{
var cmdDelete = new OdbcCommand("delete from mytable where id=?",
connection);
cmdDelete.Parameters.Add("@id", OdbcType.Text).Value = Textbox1.Text;
cmdDelete.ExecuteNonQuery();
}
catch ( Exception ex )
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
如果使用Sql Server:
using System.Data.SqlClient;
SqlConnection
SqlCommand
SqlDbType
例如,将您需要的XXXXDbType
与转换一起使用:
...("@id", SqlDbType.Int).Value = Convert.ToInt32(Textbox1.Text) ;