在sql db中插入一个值,cmd.executenonquery发生错误 [英] inserting a value into the sql db, error at cmd.executenonquery
本文介绍了在sql db中插入一个值,cmd.executenonquery发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我是大学项目的新手!我正在尝试将值插入密码列,并在错误中插入cmd.ExecuteNonQuery();显示列'Name'不允许使用NULL字符
错误MSG:无法将值NULL插入列'Name',表'jimmy.dbo.Emplo';列不允许空值。 INSERT失败。
Hello i'm a newbie doing this for college project! I'm trying to insert the value into the Password column and in error at the cmd.ExecuteNonQuery(); shows that column 'Name' doesn't allow NULL characters
ERROR MSG:Cannot insert the value NULL into column 'Name', table 'jimmy.dbo.Emplo'; column does not allow nulls. INSERT fails.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=JIMMY-PC;initial Catalog=jimmy;Integrated Security=true");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
using(SqlCommand cmd = new SqlCommand("Insert into Emplo ([Name],[Designation],[Dept],[D O B],[Sex],[Address]) values (@Name,@des,@dept,@DOB,@Sex,@Address)", con))
{
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@des", SqlDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("@dept", SqlDbType.VarChar).Value = TextBox3.Text;
cmd.Parameters.Add("@DOB", SqlDbType.SmallDateTime).Value = TextBox4.Text;
cmd.Parameters.Add("@Sex", SqlDbType.VarChar).Value = RadioButton1.SelectedItem.Text;
cmd.Parameters.Add("@Address", SqlDbType.VarChar).Value = TextBox5.Text;
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Registered successfully......!')</script>");
}
//string c=CreateRandomPassword();
using (SqlCommand cmd = new SqlCommand("insert into Emplo([Password]) values (@pass)", con))
{
cmd.Parameters.Add("@pass", SqlDbType.VarChar).Value = CreateRandomPassword(6);
cmd.ExecuteNonQuery();
}
con.Close();
}
public static string CreateRandomPassword(int PasswordLength)
{
string allowdChars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
Random randNum = new Random();
char[] chars = new char[PasswordLength];
int allowedCharCount = allowdChars.Length;
for (int j = 0; j < PasswordLength; j++)
{
chars[j] = allowdChars[(int)((allowdChars.Length) * randNum.NextDouble())];
}
return new string(chars);
}
}
推荐答案
仅回答从未答复的队列中删除 - 由OP解决。
Answered only to remove from unanswered queue - solved by OP.
这篇关于在sql db中插入一个值,cmd.executenonquery发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文