2014-11-17 53 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#代码中写所有这些。