2014-03-25 60 views
0

我正在嘗試使用代碼創建表。如何創建一個在單詞之間有空格的表?

這是我的代碼。

private void btnOK_Click(object sender, EventArgs e) 
{ 
    if (con.State == ConnectionState.Open) { con.Close(); } 
    con.Open(); 
    string s = "CREATE TABLE "+"" + rchtxtFieldCode.Text + " "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")"; 
    SqlCommand cmd = new SqlCommand(s, con); 
    if (cmd.ExecuteNonQuery() >= 1) 
    { 
     MessageBox.Show("created"); 
    } 
    con.Close(); 
} 

它創建表如果表名具有單個字..這正顯示出異常,如果存在的話之間的空間(例如:銷售信息)

+1

請爲此數據庫添加標籤 –

回答

0

只需添加盒括號:

string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")"; 
         //^_______________________________^ 
1

如果這是你使用SQL Server方括號:

string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " ([" + rchFieldTitle.Text + "] " + combDataType.Text + "" + ")"; 

事實上,你應該總是使用方括號來阻止這類錯誤的發生。

同時確保您正在清理您的字符串,否則您可能會遇到SQL注入問題。

0

不要在表或字段names.In這個空間,嘗試改變查詢用方括號,即

例如,

sqlString = "CREATE TABLE [All Students]" 
0

使用此代碼,我認爲它會給你的願望輸出。

private void btnOK_Click(object sender, EventArgs e) 
    { 
     if (con.State == ConnectionState.Open) { con.Close(); } 
     con.Open(); 
     string s = "CREATE TABLE '"+rchtxtFieldCode.Text + "'(" +"'"+rchFieldTitle.Text +"'" + combDataType.Text + "" + ")"; 
     SqlCommand cmd = new SqlCommand(s, con); 
     if (cmd.ExecuteNonQuery() >= 1) 
     { 
      MessageBox.Show("created"); 
     } 
     con.Close(); 
    } 
相關問題