0

我正在实现一个使用 SQL 服务器数据库的 C# 桌面应用程序。

我有这个代码:

SqlConnection cn = new SqlConnection(@"Data Source=PC;Initial Catalog=FRAT_DB;Integrated Security=True");
SqlCommand cmdSelect = new SqlCommand("select MAX(PhotoID) from Photo", cn);
cn.Open();
SqlDataReader MaxID_Selector = cmdSelect.ExecuteReader();
double maxID = 0;
while (MaxID_Selector.Read())
{
    if (MaxID_Selector[0].ToString().Trim() != "") 
    {
        maxID = Convert.ToInt64(MaxID_Selector[0].ToString());
    }
}
maxID = maxID + 1;
cn.Close();

SqlCommand cmdb = new SqlCommand(@"IF EXISTS(SELECT * FROM Person WHERE PersonID = @personID) BEGIN  UPDATE Person SET PersonID = @PersonID, Name= @Name, Age= @Age,P_Group=@P_Group, Email= @Email END ELSE BEGIN INSERT INTO Person(PersonID,Name,Age,P_Group,Email) values(@PersonID,@Name,@Age,@P_Group,@Email)", cn);

cmdb.Parameters.AddWithValue("@PersonID", personID);
cmdb.Parameters.AddWithValue("@Name", textBox1.Text);
cmdb.Parameters.AddWithValue("@Age", textBox2.Text);
cmdb.Parameters.AddWithValue("@P_Group", textBox6.Text);
cmdb.Parameters.AddWithValue("@Email", textBox5.Text);`

当我运行程序并尝试保存信息时,我收到以下错误消息:Syntax Error Near ')'

有什么解决办法吗?

4

2 回答 2

8

看起来您在插入后缺少“结束”。这是未经测试的,但请尝试以下操作:

SqlCommand cmdb = new SqlCommand(@"IF EXISTS(SELECT * FROM Person WHERE PersonID = @personID) 
                                       BEGIN  
                                           UPDATE Person SET PersonID = @PersonID, Name= @Name, Age= @Age,P_Group=@P_Group, Email= @Email 
                                       END 
                                   ELSE 
                                       BEGIN 
                                           INSERT INTO Person(PersonID,Name,Age,P_Group,Email) values(@PersonID,@Name,@Age,@P_Group,@Email) 
                                       END ", cn
                                 );
于 2012-05-12T04:35:37.270 回答
1

您在插入后错过了“结束”,在第二个插入语句中,请尝试以下操作:

SqlCommand cmdb = new SqlCommand(@"IF EXISTS(SELECT * FROM Person WHERE PersonID = @personID) BEGIN UPDATE Person SET PersonID = @PersonID, Name= @Name, Age= @Age,P_Group=@P_Group, Email= @Email END ELSE BEGIN INSERT INTO Person(PersonID,Name,Age,P_Group,Email) values(@PersonID,@Name,@Age,@P_Group,@Email) END ", cn);
于 2012-05-12T05:11:45.070 回答