使用C#插入来自阵列线到SQL Server 2012 [英] Using C# to Insert lines from an array into SQL Server 2012

查看:94
本文介绍了使用C#插入来自阵列线到SQL Server 2012的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早些时候我张贴了这个code,但它是更乱,部分被注释掉,而我是用串联接入到数据库中。有人告诉我,把它清理干净,挑战是要使用参数,并要求更简洁的问题。有了这样说,到数据库的连接提供给我,大部分是伪code。与一些直接的命令。

1)是我的try-catch设置是否正确?

2)服务器=本地主机的红色下划线,它说,它无法字符串转换为System.Data.SqlClient.SqlConnection

3)数据库和由于Lab1都强调说,它不会在目前的情况下是否存在?这是什么意思?

4)Trusted_connection和是具有相同的错误消息为#3。

5)我不知道以后cmd.Connection =,这就是为什么它注释掉和之后都有一个问号放什么。

6)是我varname1.Close();在正确的位置?我觉得这是有道理的,它实际上在过去的2收盘括号去了?

7)在捕捞的SQLException下划线和错误说类型或命名空间的SQLException找不到。我发现从计算器另一个用户说问这个问题,并有人抓设立这样回应一个try-catch所以我复制它。

8)我想弄清楚的参数,是我的设置是否正确?所有我是1文本框,其中用户输入的数据,并将其输入到一个数组。 名是学生在数据库属性的名称,我只是做了@Name作为一个变量?我发现了一个参数例如,从其他用户也计算器和实物形式的比赛我的。

 公共静态INT计数= 0;
保护无效btnDisplay_Click(对象发件人,EventArgs的发送)
{
    尝试
    {
        System.Data.SqlClient.SqlConnection varname1 =新System.Data.SqlClient.SqlConnection();
        varname1 =服务器= localhost的;
        数据库= Lab1内;
        Trusted_connection = YES;
        varname1.Open();
        System.Data.SqlClient.SqlCommand CMD =新System.Data.SqlClient.SqlCommand();
       // cmd.Connection =(?)
        cmd.CommandText =删除从学生;
        cmd.ExecuteNonQuery();     的for(int i = 0;反> =我;我++)
     {
        cmd.CommandText =INSERT INTO线(名称)+VALUES(@Name);
        cmd.Parameters.AddWithValue(@名称,studentList [I]);
            反++;
     }
    varname1.Close();
   }
    赶上(SQLEXCEPTION EX)
    {
        lbl5.Text =连接不能建立;
    }
}


解决方案

您需要找到一个很好的资源(或几个),并学习如何做出正确的数据库调用。 这里有一个。下面是另一个,创建连接字符串。

我没有测试以下,但这样的事情应该工作。

 使用(VAR康恩=新System.Data.SqlClient.SqlConnection(服务器= LOCALHOSTDatabase = Lab1内; Trusted_Connection = TRUE;))
{
    conn.Open();    使用(VAR CMD =新的SqlCommand(删除学生,康涅狄格州))
    {
        cmd.ExecuteNonQuery();
    }    使用(VAR CMD =新的SqlCommand(插入线(名称)VALUES(@Name),康涅狄格州))
    {
        的for(int i = 0;反> =我;我++)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue(@名称,studentList [I]);
            cmd.ExecuteNonQuery();
        }
        反++;
    }
}

至于你的一些其他问题...

1 - 你的try / catch是设置好

#6 - 不要打扰调用关闭() - 使用使用

#7 - 异常名称看起来还好。你有使用System.Data.SqlClient的; 在窗体的顶部?你可能会由此及彼,因为code的其他线路与错误...很难说的错误。

#8 - 这看起来不错

Earlier I posted this code but it was much more messy, parts were commented out, and I was using concatenation to INSERT to the database. I was told to clean it up, challenged to use parameters, and ask more concise questions. With that being said, the connection to the database was given to me with mostly pseudo-code with some direct commands.

1) Is my Try-Catch set up correctly?

2) "server = LOCALHOST" is underlined in red, it says it can't convert 'string' to System.Data.SqlClient.SqlConnection'

3) "Database" and "Lab1" are underlined saying it doesn't exist in current context? What does this mean?

4) "Trusted_connection" and "yes" have the same error message as #3.

5) I'm not sure what to put after "cmd.Connection = " which is why it's commented out and has a question mark after it.

6) Is my varname1.Close(); in the right spot? I feel like it makes sense for it to actually go between the last 2 closing brackets?

7) In the Catch "SqlException" is underlined and the error says "The type or namespace SqlException could not be found". I found a try-catch from another user on stackoverflow that asked the question and someone responded with the catch set up like that so I copied it.

8) I'm trying to figure out parameters, Is mine set up correctly? All I have is 1 textbox in which the user inputs data and it enters into an array. "Name" is the name of the attribute of the student in the database, and I just made up @Name as a variable? I found a parameter example from another user also on stackoverflow and kind of made match mine.

public static int counter = 0;
protected void btnDisplay_Click(object sender, EventArgs e)
{
    try
    {
        System.Data.SqlClient.SqlConnection varname1 = new System.Data.SqlClient.SqlConnection();
        varname1 = "server = LOCALHOST";
        Database = Lab1; 
        Trusted_connection = yes;
        varname1.Open();
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
       // cmd.Connection = (?)
        cmd.CommandText = "Delete From Student";
        cmd.ExecuteNonQuery();

     for(int i=0; counter >= i; i++)
     {
        cmd.CommandText = "INSERT INTO Lines (Name) " + "VALUES (@Name)";
        cmd.Parameters.AddWithValue("@Name", studentList[i]);
            counter++;
     }
    varname1.Close();
   }
    catch (SqlException ex)
    {
        lbl5.Text = "Connection could not be established";
    }
}

解决方案

You need to find a good resource (or a few) and learn how to make proper database calls. Here's one. Here's another, on creating connection strings.

I haven't tested the following, but something like this should work.

using (var conn = new System.Data.SqlClient.SqlConnection("Server=LOCALHOSTDatabase=Lab1;Trusted_Connection=True;"))
{
    conn.Open();

    using (var cmd = new SqlCommand("Delete From Student", conn))
    {
        cmd.ExecuteNonQuery();
    }

    using (var cmd = new SqlCommand("INSERT INTO Lines (Name) VALUES (@Name)", conn))
    {
        for (int i = 0; counter >= i; i++)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@Name", studentList[i]);
            cmd.ExecuteNonQuery();
        }
        counter++;
    }
}

As for some of your other questions...

#1 - Your try/catch is setup okay.

#6 - Don't bother calling Close() - use a using block

#7 - The exception name looks okay. Do you have using System.Data.SqlClient; at the top of your form? You may be getting an error here because of other lines of code with errors... hard to say.

#8 - That looks fine.

这篇关于使用C#插入来自阵列线到SQL Server 2012的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆