本文介绍了抛出异常:System.Data.dll问题中的'System.Data.SqlClient.SqlException'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
错误:
error:
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Additional information: Cannot insert the value NULL into column 'Id', table 'Login.dbo.Rota'; column does not allow nulls. INSERT fails.
The statement has been terminated.
它基本上向我的数据库添加空白数据(NULL)它不应该......我认为
表格图片: [ ]
我的代码:
its basically adding a blank data(NULL) to my database when it shouldn't be... i think
form pic: http://postimg.org/image/skqp12obj/[^]
my code:
private void button2_Click(object sender, EventArgs e)
{
const string con = "Data Source = dqq5ndqef2.database.windows.net; Initial Catalog = Login; Integrated Security = False; User ID = richardjacobs97; Password = ********; Connect Timeout = 15; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False";
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
using (SqlCommand cmd = new SqlCommand("INSERT INTO Rota (Id, Name, DateWorking) Values (@Id, @Name, @DateWorking)", connection, transaction))
{
cmd.CommandType = CommandType.Text;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@Id", dataGridView1.Rows[i].Cells["Id"].Value);
cmd.Parameters.AddWithValue("@Name", dataGridView1.Rows[i].Cells["Name"].Value);
cmd.Parameters.AddWithValue("@DateWorking", dataGridView1.Rows[i].Cells["DateWorking"].Value);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name, DateWorking FROM Rota", connection))
{
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
任何建议?
any sugguestions?
推荐答案
cmd.Parameters.AddWithValue("@Id", dataGridView1.Rows[i].Cells["Id"].Value);
可能 Id 是表格的主键,应该是自动生成的。
在这种情况下,执行以下操作可以解决您的问题
[]
希望,它有帮助:)
Probably Id is the primary key for the table and should be autogenerated.
Doing following should resolve your problem in this case
Auto increment primary key in SQL Server[^]
Hope, it helps :)
这篇关于抛出异常:System.Data.dll问题中的'System.Data.SqlClient.SqlException'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!