C#检查数据库错误中是否存在值

时间:2014-02-14 16:02:05

标签: c#

当我想检查数据库条目中是否存在程序时,会给我一个错误:

  

不支持关键字:'datasource'

我的代码:

public bool FindString(string myString)
{
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = "datasource=localhost;port=3306;username=admin;password=admin"; 
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "Create Procedure FindString(@MyString nvarchar(50)) as Begin Select * test.user Where Value = @MyString End";
        command.Parameters.AddWithValue("@MyString", myString);

        try
        {
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                return true;
            }
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
                connection.Close();
        }
        return false;
    }

使用该类的代码:

ReadData r = new ReadData();

if (r.FindString(textBox1.Text))
   MessageBox.Show("I Found it!");
else
   MessageBox.Show("I can't Find it!");

4 个答案:

答案 0 :(得分:2)

关键字“datasource”在ConnectionString配置的上下文中不存在。您应该使用“日期来源”作为两个单独的单词:

connection.ConnectionString = "data source=localhost;port=3306;username=admin;password=admin";

答案 1 :(得分:2)

如果您使用的是MySQL:SqlConnection适用于SQL Server。请改用MySqlConnection

如果您还没有用于MySQL的.Net连接器,可以下载它from here

答案 2 :(得分:0)

看两个单独的单词here数据源

答案 3 :(得分:0)

Look here我想你写错了连接字符串。正如@bejger所写,你需要写“数据源”