How To store data in Sql database in Microsoft Azure - c#

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

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

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=***********")){
//....
}

Related

error: the property connection has not initialized

I'm working on a project. i've built a form by using visual studio express 2012 for desktop window and i'm programming in c#. here is a function that i want to use in a button event:
void connect()
{
//chaine_connexion="Data Source=MILLIONNAIRE-PC\\ITS4_2017;Initial Catalog=TP_ITS4_2017;User ID=sa;Password=***********"
string chaine = GestionEnquete.Properties.Settings.Default.chaine_connexion;
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = chaine;
cnn.Open();
// test the state of the connection
if (cnn.State == System.Data.ConnectionState.Open)
MessageBox.Show("Connexion established");
else
MessageBox.Show("Connexion not established");
//déclare an object SqlCommand type
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select count(*) from Agent" +
"where codeAgent='" + TXT_LOGIN.Text.Trim() + "'" +
"and motdepasse = '" + PW_PASSWORD.Password + "'";
//cmd.Connection = cnn;
int resultat = cmd.ExecuteNonQuery();
if (resultat > 0)
{
MessageBox.Show("the user exist in the database");
Equipe a = new Equipe();
a.Show();
Hide();
}
else
MessageBox.Show("no user");
cnn.Close();
}
when i fill the form by adding a codeAgent and a password in TXT_LOGIN and PW_PASSWORD textbox, i received these messages:
Connexion established
error: the property connection has not initialized
Now when a put cmd.Connection = cnn; just before int resultat = cmd.ExecuteNonQuery();, visual studio send the error:
Execution error: incorrect syntaxe near '='.
Please i need your help.
There's a missing space after Agent:
cmd.CommandText = "select count(*) from Agent" + ...
This leads to the SQL command select count(*) from Agentwhere... causing this syntax error.
Just add a space and it should work as expected:
cmd.CommandText = "select count(*) from Agent " +
But your code is vulnerable to SQL-Injection.
You should read about parameterized queries.

Error: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I used these codes:
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection();
public Form1()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sTUDENTDataSet.login' table. You can move, or remove it, as needed.
//this.loginTableAdapter.Fill(this.sTUDENTDataSet.login);
SqlConnection con = new SqlConnection("Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True");
con.Open();
{
}
}
private void btnLogin_Click_1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
con.Open();
string UserId = txtUsername.Text;
string UserPass = txtPassword.Text;
SqlCommand cmd = new SqlCommand("Select UserId,UserPass from Login where UserId='" + txtUsername.Text + "'and UserPass='" + txtPassword.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login sucess!");
Form2 form = new Form2();
form.Show();
}
else
{
MessageBox.Show("Invalid Login Information. Please check username and password");
}
con.Close();
}
The error here is the con.Open(); that belongs here:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
con.Open();
I tried removing it because I don't know what else to do and the second error is on da.Fill(dt); So I guess the only problem that should really be fixed is the con.Open();
What should I do?
The error is in your connection string.
As a DataSource you have to specify SERVER\INSTANCE; SQLEXPRESS is usually an instance name in default installation, so try:
con.ConnectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
., (LOCAL), LOCALHOST and YourMachineName are all equivalent, referring to your own machine as a server. If your database is on another PC you have to specify its name.
Your connection string looks incomplete. While it names a server (SQLEXPRESS), it omits any mention of which data base.
Although it refers instead to LocalDB, perhaps comparing the working connection string below against yours will suggest to you what you need to add.
Data Source=(LocalDB)\v11.0;AttachDbFilename="$$WorkingDirectory$$\RGUNC_Tag_Browser\RGUNC_Tags.mdf";Integrated Security=True
The bottom line is that the error message is telling you that it cannot locate your data base with the information supplied in your connection string.

C# Query: 'System.InvalidOperationException' | Additional information: Connection must be valid and open

connectionString = #"server=localhost;database=" + lbDatabase.SelectedItem.ToString() + ";userid=root;password=;";
string query = "SELECT order_id FROM orders WHERE id = 1";
MySqlConnection connect = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(query, connect);
reader = cmd.ExecuteReader();
Hello,
I have this problem when I run the following code. I get this not so very specific error:
An unhandled exception of type 'System.InvalidOperationException'
occurred in MySql.Data.dll
Additional information: Connection must be valid and open.
If anyone could help me out I would really appreciate it,
Thank you.
The syntax for MySql Connectionstring is as follows:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Note that you are using 'userid' and 'password' instead of 'uid' and 'pwd'.
Assuming that your Connection String is Right .. Try This
connectionString = #"server=localhost;database=" + lbDatabase.SelectedItem.ToString() + ";userid=root;password=;";
string query = "SELECT order_id FROM orders WHERE id = 1";
MySqlConnection connect = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(query, connect);
connect.Open();
reader = cmd.ExecuteReader();
/*Do Whatever You Want To Do Here */
connect.Close();
You Can Refer this Link for Reference.
Exception: System.InvalidOperationException Trying to validate a login information
Hope This Helps :)

MySQL connection to phpMyAdmin created database with C#

As our question got closed yesterday, we unfortunately have to open a new one. So here goes.
This is the old question: MySQL connection with C# through PHPMyAdmin created database
Firstly, thanks for all the answers! So we have implemented Rahul and ActiveHigh's answers and updated the code. Furthermore, we have added a way to check if the connection is a success or not. Now when we try to insert data we get the error message from the catch. The test location is still the same. Here is an image of the table in the database: https://www.dropbox.com/s/g2c70ty9qb1h7bw/ScreenshotDatabase.png
Anyone have any idea what is going wrong or an idea how to debug it?
(We have checked inside phpmyadmin whether or not the table is empty with a SQL query. It is empty.
protected void Button1_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection connection;
string server = "db.cce-solutions.dk";
string database = "web626445";
string uid = "******";
string password = "******";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
DisplayMessage.Text = "Data entered succesfully.";
MySqlCommand cmd = new MySqlCommand("insert into Booking (yourName,YourEmail,YourPhone,Category,Date,Description) values(#Name,#Email,#Telephone,#Category,#Date,#Description)", connection);
cmd.Parameters.AddWithValue("#Name", YourName.Text);
cmd.Parameters.AddWithValue("#Email", YourEmail.Text);
cmd.Parameters.AddWithValue("#Telephone", YourPhone.Text);
cmd.Parameters.AddWithValue("#Category", Category.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Date", "test");
cmd.Parameters.AddWithValue("#Description", Description.Text);
cmd.ExecuteNonQuery();
}
else
{
DisplayMessage.Text = "Database connection failed.";
}
}
catch (Exception ex)
{
DisplayMessage.Text = "Error occured. Please try again later.";
}
connection.Close();
We found out we had assigned erroneous column names. In the insert statement we wrote yourName, yourEmail and so on (as you can see below) which needed to be changed to Name, Email, and so on.
MySqlCommand cmd = new MySqlCommand("insert into Booking (yourName,YourEmail,YourPhone,Category,Date,Description) values(#Name,#Email,#Telephone,#Category,#Date,#Description)", connection);
Furthermore we removed the if loop since we did not need it and added a throw to the catch to get more detailed feedback. Hope this can help anyone stuck in the same problem.
Don't be us - check your column names! ;)

Getting error SqlException was unhandled by user code

I'm creating a Registration form for new user sign up. Im getting the following error. I searched for solution on google, but none of them helped me.
Error : 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
Could you please help me out with this?
Code :
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label1.Text = "User Name is Already Exist";
}
else
{
Label1.Text = "UserName is Available";
}
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
String str = "Insert into regform values ( '" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Session["name"] = TextBox1.Text;
Response.Redirect("Default.aspx");
con.Close();
}
}
Your connection string seems off
Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;
Using the AttachDbFilename=... element indicates you're using SQL Server Express, but the Express default installation would be using the SQLEXPRESS instance name - so your connection string should be
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;
Have you tried with this connection string? Any luck?
If that doesn't work - can you make sure what edition of SQL Server you have installed? Connecting to it in Management Studio - what do you use as server name?? And if you're connected - what does SELECT ##Version return?
utilize this example taken from Retrieving Data Using a DataReader
you will see quickly where you are making the slight code mistake
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
change your code here
SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
Either create a Property or even better a Stored Procedure
The exception suggests that your connection string is wrong.
Isn't Initial Catalog=InstanceDB missing from your connection string? Where InstanceDB is the name of your database.
Use command parameters! If you don't, you will face several issues:
You will be threatened by SQL injection attacks!
You will have to deal with the special handling of null entries.
You will have to escape quotes in strings.
You will have to use the right formatting for date values.
Lengthy string concatenations look ugly.
SqlCommand cmd = new SqlCommand(
"SELECT * FROM regform WHERE username = #usr", con);
cmd.AddWithValue("#usr", TextBox1.Text);
Do the same for the insert statement.

Categories

Resources