2014-11-17 52 views
0

我想將數據存儲在sqlserver中,並且能夠使用此代碼。現在我想檢查表是否存在,而不是插入數據或創建新表並插入數據。所以,我需要幫助... thnku嘗試將數據存儲到sqlserver中

SqlConnection con = new SqlConnection("Data Source=PRAWAT; Initial Catalog=StudentData ;Integrated security=true; "); 

string query = "insert into NewValidStudentData(StudentId,Name,Marks) values (@StudentId,@Name,@Marks);"; 

SqlCommand cmd = new SqlCommand(); 
SqlDataAdapter da = new SqlDataAdapter(); 
da.InsertCommand = new SqlCommand(query, con); 

con.Open(); 

da.InsertCommand.Parameters.Clear(); 
da.InsertCommand.Parameters.AddWithValue("@StudentId", System.Data.SqlDbType.NVarChar).Value = value[0]; 
da.InsertCommand.Parameters.AddWithValue("@Name", System.Data.SqlDbType.NVarChar).Value = value[1]; 
da.InsertCommand.Parameters.AddWithValue("@Marks", System.Data.SqlDbType.NVarChar).Value = value[2]; 

da.InsertCommand.ExecuteNonQuery(); 

con.Close(); 
+0

當你對沒有這個表的數據庫運行這個錯誤時,你看過錯誤嗎? – JeffO

+0

在try/catch/create表中換行。或者在應用程序中啓動查詢information_schema.tables,以確定是否需要應用任何遷移。或者閱讀關於遷移的內容,這是許多框架的一個特性,它們的功能完全相同。 – MatthewMartin

+0

更好地在存儲過程中執行SQL。如果您需要對SQL進行更改,請修改存儲的proc,而不是C#應用程序。 –

回答

0

您可以編輯您的查詢是這樣的:

IF (EXISTS 
    (SELECT * FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_SCHEMA = 'YourSchemaName'// if you don't know the name, try 'dbo' 
    AND TABLE_NAME = 'NewValidStudentData')) 
BEGIN 
    INSERT INTO NewValidStudentData(StudentId, Name, Marks) 
    VALUES (@StudentId, @Name, @Marks);"; 
END 

只是包裝這個查詢爲一個字符串,執行相同的。這樣,您就可以控制表的存在並將數據插入到數據庫服務器的單個調用中。

0

首先檢查,如果你的表在這個片段中存在的(另見本answer):

bool exists; 
string tableName = "WhatEverItIs"; 

try { 
    // ANSI SQL way. Works in PostgreSQL, MSSQL, MySQL. 
    var cmd = new OdbcCommand(
     "select case when exists((select * from information_schema.tables where table_name = '" + tableName + "')) then 1 else 0 end"); 

    exists = (int)cmd.ExecuteScalar() == 1; 
} catch { 
    try { 
     // Other RDBMS. Graceful degradation 
     exists = true; 
     var cmdOthers = new OdbcCommand("select 1 from " + tableName + " where 1 = 0"); 
     cmdOthers.ExecuteNonQuery(); 
    } catch { 
     exists = false; 
    } 
} 

然後如果不存在的話:

if(!exists) { 
    var createTableSql = "CREATE TABLE WHAT_YOUR_TABLE_SCHEME_IS"; 
    // execute a command with above createTableSql, to create your table 
} 

,然後執行其餘的代碼

0

StudentId as NVARCHAR?學生證是否有字符?

IF NOT EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[NewValidStudentData]') AND type in (N'U')) 

BEGIN 
CREATE TABLE [dbo].[NewValidStudentData](
StudentId NVARCHAR(10), 
Name NVARCHAR(100), 
Marks NVARCHAR(3) 
) 

END 

注意:我建議在存儲過程中處理這個問題,而不是在c#代碼中寫所有這些。