使用 select from 从表中获取值以存储在插入表中
Posted
技术标签:
【中文标题】使用 select from 从表中获取值以存储在插入表中【英文标题】:Get values from a table with select from to be stored in insert into table 【发布时间】:2020-08-11 18:33:27 【问题描述】:我有一个项目有两个窗口,其中一个是登录页面,SQL 设置为select from
,另一个页面是学生,设置为insert into
。
我希望表 student
中的列 username
以某种方式出现在插入表中。
public string saveduser;
private void button_Click(object sender, RoutedEventArgs e)
SqlConnection sqlCon = new SqlConnection(@"Data Source = root\SQLEXPRESS; Initial Catalog =Log-In; Integrated Security = True");
try
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
string query = "SELECT COUNT(1) FROM Login WHERE Username = @Username AND password = @password AND usertype = @usertype";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("@Username", txtUsername.Text);
sqlCmd.Parameters.AddWithValue("@password", txtPassword.Text);
......
学生页面:
private void button_Click(object sender, RoutedEventArgs e)
Login aa = new Login();
string newsaveduser = aa.saveduser;
using (var Con = new SqlConnection(@"Data Source=root\SQLEXPRESS; Initial Catalog=Log-In; Integrated Security=True"))
Con.Open();
var table = "INSERT INTO Student (username, DepartureCity, ArrivalCity, DateOfDeparture, DateOfReturn) VALUES (@username, @DepartureCity, @ArrivalCity, @DateOfDeparture, @DateOfReturn)";
using (var cmd = new SqlCommand(table, Con))
// again here trying to use the textbox but it keep giving me error SqlParameter unitsParam = cmd.Parameters.AddWithValue("@username", newsaveduser);
if (aa.saveduser == null)
unitsParam.Value = DBNull.Value;
cmd.Parameters.AddWithValue("@DepartureCity", fromtxt.Text);
cmd.Parameters.AddWithValue("@ArrivalCity", Totxt.Text);
cmd.Parameters.AddWithValue("@DateOfDeparture", date_time_picker.Text);
cmd.Parameters.AddWithValue("@DateOfReturn", date_time_picker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted successfully");
我在这段代码中遇到的错误:
附加信息:无法将值 NULL 插入“用户名”列、“Log-In.dbo.Student”表;列不允许空值。插入失败
【问题讨论】:
cmd.Parameters.AddWithValue("@username", your_userName);
【参考方案1】:
您的学生页面上似乎忘记添加用户名
cmd.Parameters.AddWithValue("@Username", txtUsername.Text);
cmd.Parameters.AddWithValue("@DepartureCiry", fromtxt.Text);
cmd.Parameters.AddWithValue("@ArrivalCity", Totxt.Text);
cmd.Parameters.AddWithValue("@DateOfDeparture", date_time_picker.Text);
cmd.Parameters.AddWithValue("@DateOfReturn", date_time_picker1.Text);
【讨论】:
以上是关于使用 select from 从表中获取值以存储在插入表中的主要内容,如果未能解决你的问题,请参考以下文章