将值从 datagridview 插入到 sql
Insert value from datagridview to sql
我想将数据从 datagridview 插入数据库,但没有成功第一个按钮从 xls 导入数据,第二个按钮应该将所有数据插入数据库,而不仅仅是一条记录。我该如何解决?
private void button8_Click(object sender, EventArgs e)
{
string stringconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox2.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection cons = new OleDbConnection(stringconn);
OleDbDataAdapter dat = new OleDbDataAdapter("Select * from [Sheet1$]", cons);
dat.Fill(dt);
dataGridView1.DataSource = dt;
}
private void button9_Click(object sender, EventArgs e)
{
try
{
load();
conn.Open();
string col1 = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col2 = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col3 = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string insert_sql = "INSERT INTO humans VALUES('" + col1 + "','" + col2 + "','" + col3 + "')";
da = new NpgsqlDataAdapter(insert_sql, conn);
da.SelectCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
可能问题出在数据类型上,因为列值是字符串
所以你应该像下面这样传递字符串值,试试这个:
string query = "Insert into [User].[dbo].[songsN1] (songsName,path) Values (@c1,@c2,c3)";
command.Parameters.AddWithValue("@c1", col1);
command.Parameters.AddWithValue("@c2",col2);
command.Parameters.AddWithValue("@c3", col3);
我想将数据从 datagridview 插入数据库,但没有成功第一个按钮从 xls 导入数据,第二个按钮应该将所有数据插入数据库,而不仅仅是一条记录。我该如何解决?
private void button8_Click(object sender, EventArgs e)
{
string stringconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox2.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection cons = new OleDbConnection(stringconn);
OleDbDataAdapter dat = new OleDbDataAdapter("Select * from [Sheet1$]", cons);
dat.Fill(dt);
dataGridView1.DataSource = dt;
}
private void button9_Click(object sender, EventArgs e)
{
try
{
load();
conn.Open();
string col1 = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col2 = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col3 = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string insert_sql = "INSERT INTO humans VALUES('" + col1 + "','" + col2 + "','" + col3 + "')";
da = new NpgsqlDataAdapter(insert_sql, conn);
da.SelectCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
可能问题出在数据类型上,因为列值是字符串 所以你应该像下面这样传递字符串值,试试这个:
string query = "Insert into [User].[dbo].[songsN1] (songsName,path) Values (@c1,@c2,c3)";
command.Parameters.AddWithValue("@c1", col1);
command.Parameters.AddWithValue("@c2",col2);
command.Parameters.AddWithValue("@c3", col3);