我没有得到,如何在单击按钮上插入和更新C#WinForms中的数据。
private void save_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";
cn.Open();
string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
string clas = null;
clas = comboBox1.Text;
string section = null;
section = comboBox2.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");
SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
答案 0 :(得分:0)
您可以在插入前添加删除:
with open('test.csv', 'rb') as input, open('first_test.csv', 'wb') as output:
writer = csv.writer(output)
for row in csv.reader(input):
if (('Urology' in row[1]) or ('Urologist' in row[1]) or ('Urologists' in row[1]) or ('MD' in row[1]) or ('D.name' in row[1])):
writer.writerow(row)
private void save_Click(object sender, EventArgs e)
{
DeletePerson(id); // add this
SqlConnection cn = new SqlConnection();
...
}
public void DeletePerson(int id)
{
using(SqlConnection connection = new SqlConnection(credentials))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "delete from studetail where someUniqeIdColumn = " + id;
cmd.ExecuteNonQuery();
}
}
负责处理连接。 答案 1 :(得分:0)
首先关闭SQL查询是不对的。它看起来应该如下所示:
INSERT INTO studetail (columnName1, columnName2, ...columnNameN)
VALUES (value1, value2, ...valueN);
列名称是您希望插入数据的列,值是您希望插入到所述列中的数据。
您还应该通过在connection语句中包装连接来处置连接。
using(var con = new SqlConnection(connectionString))
{
con.Open();
//rest of code that needs a connection here
}
此外,您需要警惕SQL注入。我强烈建议来自MSDN网站的reading this示例。它将为您提供一个使用SQL Update并使用SqlCommand.Paramaters
属性来避免SQL注入的示例。
如果您还没有数据库表中的主键,那么您可以唯一地识别表中的每条记录。
要对同一按钮执行更新和保存,您需要检查正在编辑的数据是否已存在行。当主要派对派上用场时。您需要检查数据库以查看记录是否已存在
SELECT 1 FROM studetail WHERE <Condition>
WHERE
条件将是您在表格中唯一标识(主键)行的方式。如果表中的行是唯一标识的,则如果存在值,则上述SQL语句将返回1
,这意味着如果不存在记录,您可以UPDATE
或0
,这样您就可以{ {1}}