conn.Open();
string query = "INSERT INTO Film (Film, Jaartal, Cijfer) VALUES ('" + filmnaam + "','" + jaartal + "','" + cijfer + "')";
string LastID = "SELECT TOP 1 Id FROM Film ORDER BY Id DESC";
SqlCommand cmd = new SqlCommand(query, conn);
SqlCommand cmd2 = new SqlCommand(LastID, conn);
cmd.ExecuteNonQuery();
using (SqlDataReader dr = cmd2.ExecuteReader())
{
while (dr.Read())
{
string ID = dr["Id"].ToString();
string add= "INSERT INTO GenreFilm (FilmId) VALUES ('" + ID + "')";
SqlCommand cmd3 = new SqlCommand(add, conn);
cmd3.ExecuteNonQuery();
}
}
我正在尝试将my(LastID)查询的值(ID)添加到我的数据库表中。但我似乎无法做对。以上是我现有的代码。任何帮助/提示将不胜感激!
答案 0 :(得分:1)
这个并没有直接提供解决方案,而是要注意记住@ADyson指示参数(SQL-Injection)的内容以及@Dimitry指示允许数据库获取值的内容您。希望这会有所帮助。
代码中包含注释。第一类DemoForOperations显示了如何在第二类Operations中调用该方法。当然,您可以在任何地方的操作中调用insert方法。
using System;
using System.Data.SqlClient;
namespace StackOverFlowSample
{
public class DemoForOperations
{
public void TheDemo()
{
var ops = new Operations();
var firstName = "Karen";
var lastName = "Payne";
var returningNewId = 0;
if (ops.SampleInsert(firstName,lastName,ref returningNewId))
{
// success, returningNewId has the new key value which can be
// used for whatever you want e.g. as a value for another query.
}
else
{
// failed, you can use the following the
// figure out the issue
var exceptionMessage = ops.Exception.Message;
}
}
}
public class Operations
{
private Exception exception;
public Exception Exception { get { return exception; } }
/// <summary>
/// Insert a record
/// </summary>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
/// <param name="NewIdentifier">
/// pass in a valid int by ref
/// </param>
/// <returns>
/// true if successful, false otherwise and will set the property
/// Exception so that the caller can see what went wrong
/// </returns>
public bool SampleInsert(string FirstName, string LastName, ref int NewIdentifier)
{
// here we create the connection new but of course a connection can be created
// outside of the method that is in-scope of this method
using (SqlConnection cn = new SqlConnection() { ConnectionString = "TODO" })
{
// setup for insert using parameters
// along with a secondary query to return the new primary key value
var statement = "INSERT INTO Contacts (FirstName,LastName) " +
"VALUES (@FirstName,@LastName); " +
"SELECT CAST(scope_identity() AS int);";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn;
cmd.CommandText = statement;
try
{
// setup our parameters
cmd.Parameters.AddWithValue("@FirstName", FirstName);
cmd.Parameters.AddWithValue("@LastName", LastName);
cn.Open();
// get new primary key
NewIdentifier = Convert.ToInt32(cmd.ExecuteScalar());
return true;
}
catch (Exception ex)
{
exception = ex;
return false;
}
}
}
}
}
}