繁体   English   中英

如何知道是否已建立连接

[英]How to know if connection has been made

我正在尝试使用ado.net使用c#访问和插入数据。 我的计算机中安装了sql服务器,因此我觉得计算机名称将是服务器名称。 以下是我用来连接数据库的步骤。

private void dbButton_Click(object sender, EventArgs e)
    {
         connectionString = "Server = ITSL-SALT-33; Database = sampleADO; User Id = sa; Password = abcd;";
         try
         {
             SqlConnection conn = new SqlConnection(connectionString);
             conn.Open();
             MessageBox.Show("Successfully connected to the database.");
             insertButton.Enabled = true;
             loadButton.Enabled = true;

         }


         catch (Exception exc)
         {
             Console.WriteLine(exc.ToString());
             MessageBox.Show("Connection attempt failed");
         }
    }

下面是插入按钮的代码:

private void insButton_Click(object sender, EventArgs e)
    {
       cmdString="INSERT INTO books (name,author,price) VALUES (@val1, @va2, @val3)";

        SqlCommand comm = new SqlCommand();

    comm.Connection = conn;
    comm.CommandText= cmdString;
    comm.Parameters.AddWithValue("@val1", txtBook.Text);
    comm.Parameters.AddWithValue("@val2", txtAuthor.Text);
    comm.Parameters.AddWithValue("@val3", txtPrice.Text);
    comm.Parameters.AddWithValue("@val3", txtComments.Text);
    try
    {
        MessageBox.Show(conn.DataSource);
        Console.WriteLine(comm.ExecuteNonQuery());
        Console.ReadLine();

    }
    catch(Exception exc)
    {
        MessageBox.Show("In Insert catch");

    }
}

当我尝试插入数据时,它总是在消息框中显示“插入插入”。 我无法理解问题出在哪里或缺少任何步骤。 我是使用数据库或sql知识的新手,只是想学习如何与.net中的数据库进行交互。 请指导。

我认为将INSERT查询中的@va2更改为@val2只是一个小错误,它现在应该可以工作了。

cmdString="INSERT INTO books (name,author,price) VALUES (@val1, @ va2@val3)";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM