c# - 如何在 Microsoft Azure 中的 Sql 数据库中存储数据

标签 c# asp.net sql-server azure

当我将数据存储在 Microsoft Azure 云中时,我遇到了这个问题。

此处错误日志:

Server Error in '/' Application. A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

这是我的代码:

protected void Button1_Click(object sender, EventArgs e)
{
    int userId = 0;

    SqlConnection con = new SqlConnection("Data Source=asimo.database.windows.net;Initial Catalog=asimo;Persist Security Info=True;User ID=veeraiyan;Password=***********");
    con.Open();
    SqlCommand cmd = new SqlCommand("insert into registration(username,password,email)values('" + txtusername.Text + "','" + txtpassword.Text + "','" + txtemail.Text + "')", con);
    cmd.Parameters.AddWithValue("@username", txtusername.Text.Trim());
    cmd.Parameters.AddWithValue("@password", txtpassword.Text.Trim());
    cmd.Parameters.AddWithValue("@email", txtemail.Text.Trim());
    userId = cmd.ExecuteNonQuery();
    con.Close();

    string message = string.Empty;
    switch (userId)
    {
        case -1:
            message = "Username already exists.\\nPlease choose a different username.";
            break;
        case -2:
            message = "Supplied email address has already been used.";
            break;
        default:
            message = "Registration successful.\\nUser Id: " + userId.ToString();
            break;
    }
    ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
}

最佳答案

Azure Sql Server 数据库的连接字符串应写为

string cnString = @"Data Source=tcp:asimo.database.windows.net,1433;
                   Database=asimo;Trusted_Connection=False;
                   User ID=veeraiyan@asimo;Password=***********;
                   Encrypt=True;";

也就是说,插入记录和检索 IDENTITY 列 UserID 的代码未按应有的方式进行参数化。

正确的做法如下

string cmdText = @"insert into registration
                   (username,password,email)
                   values(@username, @password, @email);
                   SELECT SCOPE_IDENTITY()";
using(SqlConnection con = new SqlConnection(cnString))
using(SqlCommand cmd = new SqlCommand(cmdText, con))
{
    con.Open();
    cmd.Parameters.AddWithValue("@username", txtusername.Text.Trim());
    cmd.Parameters.AddWithValue("@password", txtpassword.Text.Trim());
    cmd.Parameters.AddWithValue("@email", txtemail.Text.Trim());
    userId = Convert.ToInt32(cmd.ExecuteScalar());
    ...

请注意,要检索 UserID,您不会获得 ExecuteNonQuery 的返回值。此方法仅返回命令插入的行数。相反,您可以将两个命令放在一起,第一个命令插入记录,第二个命令返回连接生成的最后一个 IDENTITY 的值。使用的方法是 ExecuteScalar,它返回第一行的第一列(来自最后一个 SELECT 语句)。

关于c# - 如何在 Microsoft Azure 中的 Sql 数据库中存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39676582/

相关文章:

c# - 有没有办法确定文件是否已在 C# 中执行?

c# - 匿名方法源码

sql - 如何在 SELECT T-SQL 命令的结果集中包含返回的行总数?

sql - 递归 SQL Server 查询

c++ - SQLBindCol()/SQLFetch() 返回尾随空格

c# - 如何使用 EF 为 ASP.NET Core 定义索引?

非域 Windows 环境中的 C# 编程远程文件夹/文件身份验证

c# - Ember.js 查找从 webapi Controller 返回的第一个数据属性的模型

c# - 如何通过保存对话框在 ASP.NET MVC 中从 Azure 下载 PDF 文件

asp.net - 让鼠标指针变成手来点击按钮