[英]How can I save a column value to a variable in SQL C#?
I am using windows forms C# and SQL. 我正在使用Windows窗体C#和SQL。 I have a table consists of two column:
我有一个表,由两列组成:
Column1 = myID (primary key and unique ID) Column1 = myID(主键和唯一ID)
Column2 = DateTime. Column2 =日期时间。
The following code inserts date/Time into the table: 以下代码将日期/时间插入表中:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
cn.Open();
SqlCommand cm = new SqlCommand("Insert into TableDate_Time (DateTime ) values (@DateTime)");
cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
cm.Parameters["@DateTime"].Value = DateTime.Now;
cm.Connection = cn;
cm.ExecuteNonQuery();
// something like: var varID = the current myID value
}
My Question is: How can I save the last row value of myID column into a variable whenever I click the button? 我的问题是:每当我单击按钮时,如何将myID列的最后一行值保存到变量中? any idea?
任何想法? Thank you
谢谢
In Sql Server (and other database systems) you could pass two commands in the same text. 在Sql Server(和其他数据库系统)中,可以在同一文本中传递两个命令。 Now T-SQL allows you to get back the last IDENTITY value generated for your connection using the command "SELECT SCOPE_IDENTITY()".
现在,T-SQL允许您使用命令“ SELECT SCOPE_IDENTITY()”来获取为连接生成的最后一个IDENTITY值。
Thus your code will be 因此,您的代码将是
private void button1_Click(object sender, EventArgs e)
{
string cmdText = @"Insert into TableDate_Time
(DateTime ) values (@DateTime);
SELECT SCOPE_IDENTITY()");
using(SqlConnection cn = new SqlConnection("...."))
using(SqlCommand cm = new SqlCommand(cmdText, cn))
{
cn.Open();
cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
cm.Parameters["@DateTime"].Value = DateTime.Now;
int id = Convert.ToInt32(cm.ExecuteScalar());
....
}
}
Instead of ExecuteNonQuery
, call ExecuteScalar
that returns the first column of the first row in the last command executed here (The SELECT). 代替
ExecuteNonQuery
,调用ExecuteScalar
,该ExecuteScalar
返回在此执行的最后一条命令(SELECT)中第一行的第一列。 Note that it is a good practice to enclose every disposable object like the connection and the command in a using statement to have a correct exit path for your code in case of exceptions (one that doesn't forget to dispose these objects) 请注意,在例外情况下(不要忘记处理这些对象),最好将每个可抛弃的对象(如连接和命令)封装在using语句中,以为代码提供正确的退出路径。
EDIT 编辑
If your ID column is not an IDENTITY
column but an uniqueidentifier
there are more problems. 如果您的ID列不是
IDENTITY
列,而是uniqueidentifier
,则会出现更多问题。 I suppose that your table has defined a default for the column ID using the NEWID() function of T-SQL 我想您的表已使用T-SQL的NEWID()函数为列ID定义了默认值
In this case you need to change your query to 在这种情况下,您需要将查询更改为
private void button1_Click(object sender, EventArgs e)
{
string cmdText = @"Insert into TableDate_Time
(DateTime ) OUTPUT INSERTED.myID values (@DateTime)";
using(SqlConnection cn = new SqlConnection("...."))
using(SqlCommand cm = new SqlCommand(cmdText, cn))
{
cn.Open();
cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
cm.Parameters["@DateTime"].Value = DateTime.Now;
Guid id = (Guid)cm.ExecuteScalar();
....
}
}
Assuming that the new ID is generated in the database via a column default, you could use the OUTPUT
clause to return the ID of the new record: 假设新的ID是通过默认列在数据库中生成的,则可以使用
OUTPUT
子句返回新记录的ID:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
cn.Open();
SqlCommand cm = new SqlCommand("INSERT INTO TableDate_Time (DateTime) OUTPUT inserted.myID VALUES (@DateTime)");
cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
cm.Parameters["@DateTime"].Value = DateTime.Now;
cm.Connection = cn;
Guid newID = (Guid)cm.ExecuteScalar();
}
Some other things to consider that are not germane you your problem: 需要考虑的其他一些事项与您的问题无关:
using
blocks so that they are closed in a timely fashion, even if there is an exception. using
块将命令和连接包装起来,以便即使有异常也能及时关闭它们。 That's easy. 这很容易。 Just add the following code:
只需添加以下代码:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
cn.Open();
SqlCommand cm = new SqlCommand("Insert into TableDate_Time (DateTime ) values (@DateTime)");
cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
cm.Parameters["@DateTime"].Value = DateTime.Now;
cm.Connection = cn;
int returnValue = 0;
SqlParameter param = new SqlParameter();
param.ParameterName = "ReturnParameter";
param.Direction = ParameterDirection.ReturnValue;
cm.Parameters.Add(param);
cm.Connection.Open();
cm.ExecuteNonQuery();
}
And in your stored procedure (or sql query) add: 并在您的存储过程(或sql查询)中添加:
DECLARE @ID int = (Select SCOPE_IDENTITY())
RETURN @ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.