使用ExecuteReader返回主键

时间:2015-11-27 10:44:01

标签: c# sql sql-server

如何从第一个查询中查找ID并返回此值,以便将其插入到query2中?这是用户在前端完成表单时需要完成的代码。我需要填充两个表,它们将通过ID“StoryID”关联,这是一个自动创建的主键。

[root@localhost spark]# sbin/start-all.sh
starting org.apache.spark.deploy.master.Master, logging to /opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/spark/sbin/../logs/spark-root-org.apache.spark.deploy.master.Master-1-localhost.localdomain.out
failed to launch org.apache.spark.deploy.master.Master:
  JAVA_HOME is not set
full log in /opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/spark/sbin/../logs/spark-root-org.apache.spark.deploy.master.Master-1-localhost.localdomain.out
root@localhost's password: 
localhost: Connection closed by UNKNOWN

1 个答案:

答案 0 :(得分:2)

最重要的 - 在SQL命令中使用参数。永远不要连接那样的字符串。你要求SQL injection攻击。

start on runlevel [2345]
stop on runlevel [!2345]

exec /path/to/script.py

要获取返回的ID,请使用string query = @" INSERT INTO UserStories (StoryNo, StoryText, ProductOwner, ProjectID) VALUES (@storyno, @userstory, @usernameData, @captureProjectID) SELECT CAST(SCOPE_IDENTITY() AS INT)"; SqlCommand myCommand = new SqlCommand(query); myCommand.Parameters.Add("@storyno", DbType.String).Value = storyno; ...

ExecuteScalar()

另外,您没有正确处理资源。如果方法中引发异常,则不会关闭int StoryIDData = (int)myCommand.ExecuteScalar(); 。你应该把它放在SQLConnection声明中。