试图将数据从一种形式移动到另一种形式,并且表格存在问题。是的,我发现这样的主题有误,并试图纠正自己,但出了点问题。
using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True"))
{
SqlDataAdapter comm = new SqlDataAdapter("INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('"+ tName.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + cbName.Text + "' and Stage = '" + cbStage.Text + "'), '" + tSurname.Text + "', '" + tMiddle.Text + "', '" + tPas.Text + "', '" + cbClinic.Text + "', '" + tAge.Text + "')", conn);
conn.Open();
DataSet ds = new DataSet();
//ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
comm.Fill(ds);
Form1 form = new Form1();
form.DataGrid.DataSource = ds.Tables[0]; //?
}
string connectionString = "Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
try
{
command.CommandText = "INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('" + metroTextBox1.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + metroComboBox1.Text + "' and Stage = '" + metroComboBox2.Text + "'), '" + metroTextBox2.Text + "', '" + metroTextBox3.Text + "', '" + maskedTextBox1.Text + "', '" + metroComboBox3.Text + "', '" + metroTextBox5.Text + "')";
command.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Added");
//here is a DataSet
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
transaction.Rollback();
}
}
答案 0 :(得分:2)
您期望查询返回结果,但是您所做的只是INSERT
语句。
要插入值,应使用ExecuteNonQuery
(see this for reference)的SqlCommand
方法。
然后,分配另一个命令:SELECT
以获取结果,然后可以用结果填充DataSet
,然后可以用它填充DataGridView
。
也:您是向SQL注入的专家,请使用参数化查询来防止自己受到此类威胁(see this for reference)。