在插入期间增加int

时间:2013-12-19 11:20:51

标签: c# .net oledbconnection

我试图在插入期间从c#.net页面增加MS Access表中的整数。

尝试以下操作时出现语法错误。还不确定我是否应该使用ExecuteNonQuery()

OleDbCommand cmd = new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(@target,(SELECT MAX(ref)+1 FROM tblTarget)", conn);

cmd.Parameters.AddWithValue("@target", TextTitle.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

4 个答案:

答案 0 :(得分:4)

tblTarget之后你错过了一个括号:

OleDbCommand cmd = 
    new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(@target,(SELECT MAX(ref)+1 FROM tblTarget))", conn);

以下是对您的代码的一点评论,请尝试使用using模式:

using(var conn = new Connection())
{
    conn.Open();
    string sql = "INSERT INTO tblTarget(target,ref) VALUES(@target,(SELECT MAX(ref)+1 FROM tblTarget))";
    OleDbCommand cmd = new OleDbCommand(sql, conn);

    cmd.Parameters.AddWithValue("@target", TextTitle.Text);

    cmd.ExecuteNonQuery();
}

答案 1 :(得分:3)

你错过了一个括号,试试:

INSERT INTO tblTarget(target,ref) VALUES(@target,(SELECT MAX(ref)+1 FROM tblTarget))

但我认为你会遇到其他问题,你需要更接近这个:

INSERT INTO tblTarget ( target, ref )
SELECT @target AS Targ, First((SELECT MAX(ref)+1 FROM tblTarget)) AS MaxRef
FROM tblTarget
GROUP BY @target;

答案 2 :(得分:2)

实现目标的正确方法是

string sql = "INSERT INTO tblTarget (target,ref) " + 
             "SELECT ?, MAX(ref)+1 FROM tblTarget";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("@target", TextTitle.Text);
cmd.ExecuteNonQuery();

答案 3 :(得分:0)

我不会通过sql或代码进行增量,我们可以使用AutoNumber数据类型来自动增加访问中的值。

string sql = "INSERT INTO tblTarget(target) VALUES(@target)";
using(var conn = new Connection())
using(OleDbCommand cmd = new OleDbCommand(sql, conn))
{
    conn.Open();
    cmd.Parameters.AddWithValue("@target", TextTitle.Text);
    cmd.ExecuteNonQuery();
}