C# Sql Client: ALTER Table doesn't work

本文关键字:work doesn Table Sql Client ALTER | 更新日期: 2023-09-27 18:07:42

我有一个代码,用于添加一些行到SQL,但它不会工作。SelectDelete工作,但ALTER TABLE命令不工作。

如果我复制并粘贴我的控制台输出到Microsoft Management Sql Query,它工作。(tmp1被填充一些名称,tmp2被填充例如CHAR(50))

编辑:我没有得到任何错误,在我的SQL服务器的日志中,我没有看到任何名为"Alter"的命令要执行。

 string tmp1, tmp2;
 tmp1 = addfrm.getTableName();
 tmp2 = addfrm.getType();
 string constring = @"Data Source=" + adr + ";Initial Catalog=" + dat + ";User ID=" + user + ";Password=" + pwd;
 try
 {
     using (SqlConnection con = new SqlConnection(constring))
     {
         string tmp = @"ALTER TABLE " + tbl + " ADD " + tmp1 + " " + tmp2;
         Console.WriteLine("Mein Befehl lautet: " + tmp);
         using (SqlCommand cmd = new SqlCommand(tmp, con))
         {
             cmd.CommandType = CommandType.Text;
             using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
             {
             }
         }
     }
 }
 catch (SqlException) 
 { 
     MessageBox.Show("Fehler"); 
 }

C# Sql Client: ALTER Table doesn't work

您没有向数据库发送SQL查询。在SqlCommand上使用ExecuteNonQuery。而不是:

using (SqlCommand cmd = new SqlCommand(tmp, con))
{
    cmd.CommandType = CommandType.Text;
    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {
    }
}
使用

using (SqlCommand cmd = new SqlCommand(tmp, con))
{
    cmd.ExecuteNonQuery();
}

适配器将不执行查询,直到adapter.Fill被调用。

您没有正确设置值。试试这个应该可以。

string tmp1, tmp2;
                tmp1 = addfrm.getTableName();
                tmp2 = addfrm.getType();
                string constring = @"Data Source=" + adr + ";Initial Catalog=" + dat + ";User ID=" + user + ";Password=" + pwd;
                try
                {
                    using (SqlConnection con = new SqlConnection(constring))
                    {
                        string tmp = @"UPDATE TABLE " + tbl + " SET Col1 = '" + temp1 +"',Col2='" + tmp2 +"'";
                        Console.WriteLine("Mein Befehl lautet: " + tmp);
                        using (SqlCommand cmd = new SqlCommand(tmp, con))
                        {
                            cmd.CommandType = CommandType.Text;
                            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                            {
    cmd.ExecuteNonQuery();
                            }
                        }
                    }
                }
                catch (SqlException) { MessageBox.Show("Fehler"); }

我只是用填充来避免它。有点乱,不过还好。多亏了说这话的Pawel。

                            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            DataTable dt = new DataTable();
                            sda.Fill(dt);
                        }