简体   繁体   中英

How To store data in Sql database in Microsoft Azure

I face this problem when I store my data in Microsoft Azure Cloud.

here error log:

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)

This is my code:

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);
}

Check out https://www.google.com/search?q=agoogle&ie=&oe=#q=agoogle+c-sharp+azure+sql+connection+string for your connection string issue. Then, as suggested in comments, change:

  SqlCommand cmd = new SqlCommand("insert into registration(username,password,email)values('" + txtusername.Text + "','" + txtpassword.Text + "','" + txtemail.Text + "')", con);

 //change your connection string to an Azure-compatible one... 

to:

  SqlCommand cmd = new SqlCommand("insert into registration(username,password,email)values(@username,@password,@email, con);

and while you're at it, change:

 SqlConnection con = new SqlConnection("Data Source=asimo.database.windows.net;Initial Catalog=asimo;Persist Security Info=True;User ID=veeraiyan;Password=***********");

to:

using(SqlConnection con = new SqlConnection("Data Source=asimo.database.windows.net;Initial Catalog=asimo;Persist Security Info=True;User ID=veeraiyan;Password=***********")){

 //....

 }

The connectionstring for an Azure Sql Server database should be written as

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

Said that, your code to insert a record and to retrieve the IDENTITY column UserID is not parameterized as it should be.

The correct approach is the following

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());
    ...

Notice that to retrieve the UserID you don't get the return value of ExecuteNonQuery. This method returns only the number of rows inserted by your command. Instead you could put two commands together, the first one inserts the record, the second one returns the value of the last IDENTITY generated by your connection. The method used is ExecuteScalar that returns the first column of the first row (from the last SELECT statement).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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