【问题标题】:Connect to SQL Server and insert values连接到 SQL Server 并插入值
【发布时间】:2016-11-08 01:32:11
【问题描述】:

我是 c# 和 .net 的新手,所以我将数据插入数据库。

首先我创建了新项目 - asp.net Web 应用程序 (v4.6.1)。然后我选择了网络表单模板。

我的web.config 文件自动添加了这一行

<connectionStrings>
    <add name="DefaultConnection" 
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication7-20161108020707.mdf;Initial Catalog=aspnet-WebApplication7-20161108020707;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings> 

这就是我与数据库的连接。

我启动了 Microsoft SQL Server Management Studio。在左侧,我有对象资源管理器,可以在其中看到我的服务器(我的计算机 - 我使用 Windows 身份验证)。有一个名为数据库的文件夹。我右键单击它并选择新数据库...我创建了名为 test 的新数据库。然后我展开测试数据库并右键单击表文件夹并选择新建->表。我添加了 2 列。 id (int) - 非 null 和 name (nchar(255)) - 非 null。我添加了 id 列作为身份。我保存了表并将其命名为 testing。

现在我在 Visual Studio 中创建了Default.aspx 页面。

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication7._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

<asp:TextBox ID="someBox" runat="server" placeholder="enter something"> </asp:TextBox>

<asp:Button ID="clickMe" runat="server" text="click" onclick=clickMe_click />

</asp:Content>

我添加到 Default.aspx.cs 中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Configuration;
using System.Data;

namespace WebApplication7
{
  public partial class _Default : Page
  {
      protected void clickMe_click(object sender, EventArgs e)
      {
        string txtBox = someBox.Text;

        System.Data.SqlClient.SqlConnection sqlConnection1 =
           new System.Data.SqlClient.SqlConnection("DefaultConnection");

        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.CommandText = "INSERT testing (name) VALUES (txtBox)";
        cmd.Connection = sqlConnection1;

        sqlConnection1.Open();
        cmd.ExecuteNonQuery();
        sqlConnection1.Close();
     }
  }
} 

我也尝试在点击函数中使用这段代码:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());

SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO testing (name) VALUES (@name)";
cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = txtBox;
cmd.Connection = conn;

conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

页面刷新以及当我将表刷新到 SQL Server Management Studio 并进行查询时:

select * from testing;
GO

它返回 0 行受影响并显示空表。

我做错了什么?


编辑:

 <connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication3-20161105080932.mdf;Initial Catalog=aspnet-WebApplication3-20161105080932;Integrated Security=True"
  providerName="System.Data.SqlClient" />
 </connectionStrings>

aspnet-WebApplication3-20161105080932 是我在服务器对象资源管理器中的数据库名称。在 db 中,我创建了表测试。

这是我的cs代码:

 protected void clickMe_click(object sender, EventArgs e)
    {
        string txtBox = someBox.Text;
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
        {
            string sql = "INSERT INTO testing (name) VALUES (@name)";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("name", SqlDbType.NVarChar).Value = txtBox;
            int rowsAffected = cmd.ExecuteNonQuery();
            conn.Close();
        }
    }

但是什么也没发生。

【问题讨论】:

  • @un-lucky,他已经在这样做了。查看发布的代码。
  • 字符串 txtBox = someBox.Text;我把它放到字符串 txtBox 中,所以我在代码的其他部分使用 txtBox。

标签: c# asp.net .net sql-server database


【解决方案1】:

这是一个本地数据库。在 Visual Studion 中,转到 View &gt; SQL Server Object Explorer &gt; (LocalDb)\MSSQLLocalDB &gt; aspnet-WebApplication7-20161108020707 以查看数据库的内容。无需启动 Microsoft SQL Server Management Studio。

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication7-20161108020707.mdf;Initial Catalog=aspnet-WebApplication7-20161108020707;Integrated Security=True"
  providerName="System.Data.SqlClient" />
</connectionStrings>

在创建与数据库的连接时,使用using(...) 块进行正确处理。

        string txtBox = someBox.Text;
        using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "INSERT testing (name) VALUES (@name)";
                cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = txtBox;
                cmd.Connection = conn;
                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();
            }
        }

样本输出:

【讨论】:

  • 喜欢提到using(...) 块。但是,尽管您稍后需要它,但打开连接是没有意义的。在使用前打开连接。
  • 我现在明白了。所以我必须在本地数据库中创建测试表?我应该将它创建到主数据库中还是创建新数据库然后在其中创建表?我的应用程序如何知道我需要哪个内部数据库?它没有在配置和代码后面的任何地方设置。
  • @KondukterCRO 因为您使用的是基于连接字符串的本地数据库,所以您应该从那里执行必要的步骤。连接上的初始目录是指正在使用的数据库。你不需要创建一个新的。您可以将连接字符串中的初始目录重命名为所需的数据库名称。在您的情况下,它当前设置为aspnet-WebApplication7-20161108020707
  • 我更新了配置文件,但仍然没有。我用新信息更新了我的问题。
  • 我明白了。我已经在 string txtBox = someBox.Text;现在我只是把它当作价值。但是现在当我更改代码时,它不会在测试表中插入任何内容。我的 cs 代码和配置代码与我的问题的更新部分完全相同。我将数据库名称更改为目录和.mdf。我使用 id 和 name 字段在该数据库中创建了表名测试...唯一的区别是我必须将 .ToString() 添加到 using 块中。
【解决方案2】:

这是一些用于执行 SQL 查询的更简洁的代码(只是我的看法)

 using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"]))
 {
     string sql = "INSERT INTO testing (name) VALUES (@name)";
     SqlCommand cmd = new SqlCommand(sql, conn);
     cmd.Parameter.Add(New SqlParameter("@name", txtBox.Text));
     int rowsAffected = cmd.ExecuteNonQuery();
     conn.Close();
 }

您还可以通过获取 cmd.ExecuteNonQuery 的返回值来获取受影响的列数。

我会检查连接字符串这里是一个链接 Here.

【讨论】:

    【解决方案3】:

    看起来您在错误的地方进行了检查。从您的连接字符串中可以清楚地看出您正在使用如下所示的本地数据库,但您可能正在检查 SSMS 中的其他数据库

    connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication7-20161108020707.mdf;
    

    同样,您发布的第二个 ADO.NET 代码是正确的,但您缺少以下代码行

    cmd.CommandType = System.Data.CommandType.Text;
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2020-09-07
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 2013-05-01
    相关资源
    最近更新 更多