尝试将数据存储到sqlserver中

时间:2014-11-17 15:39:19

标签: c#

我想将数据存储在sqlserver中,我能够使用此代码。现在我想检查表是否存在而不是插入数据或创建新表并插入数据。所以我需要帮助... thnku

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();

3 个答案:

答案 0 :(得分: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

只需将此查询包装为字符串并执行相同的操作。这样,您就可以控制表的存在,并在一次调用数据库服务器中插入数据。

答案 1 :(得分: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
}

然后,完成剩下的代码

答案 2 :(得分:0)

StudentId作为NVARCHAR?学生ID中是否包含字符?

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#代码编写所有这些。