Unable to read from Azure database - c#

I'm trying to read/write to an Azure database but I receive the following error message when using the SqlDataReader in my code below:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
I can connect to the database in SQL Server Management Studio. Any suggestions as to why this might be and how to resolve this?
My C# code:
string connectionString = "Server=tcp:[xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]#[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "SELECT [xxxxx], [xxxxx] FROM [xxxxx]";
using (SqlCommand cmd = new SqlCommand(sql))
{
using (SqlDataReader reader = Database.ExecuteReader(cmd))
{
if (!reader.Read())
{
throw new Exception("[xxxxx] not found.");
}
else
{
name = Database.GetStringValue(reader, "[xxxxx]", "");
}
}
}
}

Make sure the IP you are connecting to the database form is white listed on your database configuration in Azure. Sounds like a firewall problem to me.

I don't know how but rearranging my code to the following below resolved my issue and I could read the data that I wanted.
string connectionString = "Server=tcp: [xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]#[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
SqlConnection myConnection = new SqlConnection(connectionString);
try
{
myConnection.Open();
SqlDataReader reader = null;
SqlCommand myCommand = new SqlCommand("SELECT [xxxxx] FROM [xxxxx]", myConnection);
reader = myCommand.ExecuteReader();
if (!(reader.Read()))
throw new Exception("[xxxxx] not found.");
else
cert = reader["[xxxxx]"].ToString();
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Related

how do I avoid the startup delay when I connect to a MySQL database using c# system.data.mysqlclient visual-studio on mac

Is there a way to force sql connection when the connection is open.. For the first time I wait 20 seconds to display the data.. after that everything is ok..
I use system.data.mysqlclient library for connect to cloud sql.
The code:
void Btn_GetPlaces(System.Object sender, System.EventArgs e)
{
try
{
string cs = #"server=192.168.0.1,3306;userid=Alex;password=Alex123;database=DBMeteo";
var connection = new MySqlConnection(cs);
connection.Open();
LabelSQL.Text = "Connection has beed sucsessfully..";
var cmd = new MySqlCommand();
cmd.Connection = connection;
MySqlCommand command = new MySqlCommand($"CALL nearest3({GlobalLat}, {GlobalLong}, 1)", connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// access your record colums by using reader
LabelPlace.Text = (reader[0]).ToString();
LabelDist.Text = (reader[1]).ToString();
LabelCode.Text = (reader[2]).ToString();
}
}
connection.Close();
}
catch (Exception ex)
{
LabelSQL.Text = (ex.ToString());
}
}

Unable to connect to Postgre SQL data base

I have just installed Postgre SQL on Windows 10. I can connect to the data base via PSQL and pgAdmin fine.
The problem is that I can neither connect to the data base using C# or an .udl-test file.
My C# code:
var connection = new SqlConnection(
"Data Source=localhost;" +
"User id=postgres;" +
"Password=postgres;" +
"connection timeout=10");
connection.Open();
This gives me an exception (server not found).
SqlConnection is for SQL Server only. You could use NpgsqlConnection from Npgsql library. Simple example from library developers:
var connString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
// Insert some data
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO data (some_field) VALUES (#p)";
cmd.Parameters.AddWithValue("p", "Hello world");
cmd.ExecuteNonQuery();
}
// Retrieve all rows
using (var cmd = new NpgsqlCommand("SELECT some_field FROM data", conn))
using (var reader = cmd.ExecuteReader())
while (reader.Read())
Console.WriteLine(reader.GetString(0));
}
http://www.npgsql.org/doc/index.html

Operation is not valid due to the current state of the object in C# console application

I am trying to write simple program for console application, but I am facing this error every time.
few months ago this exact code was running fine, but now it is giving me this error,
I reinstalled my visual studio and oracle database, but then also the same error...
Please Help...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
namespace dataTestDemo
{
class Program
{
static void Main(string[] args)
{
string constr;
constr = "User Id = hr; Password = tiger; data source = localhost: 1521/ORCL; pooling = false";
try
{
OracleConnection con = new OracleConnection();
con.ConnectionString = constr;
con.open();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "select salary from employees where employee_id = 109";
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())// Here, I am getting this error..
{
Console.WriteLine("Employee Salary = " + reader.GetString(0));
}
con.close();
Console.WriteLine();
Console.WriteLine("Press Enter to continue...");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.InnerException);
Console.WriteLine(ex.Data);
Console.ReadLine();
}
}
}
}
Error:
Operation is not valid due to the current state of the object.
System.Collections.ListDictionaryInternal
enter image description here
I don't see where you are setting your connection on the command object, and you also should open the connection.
OracleConnection con = new OracleConnection();
con.ConnectionString = constr;
// Open the connection
con.Open();
OracleCommand cmd = new OracleCommand();
// Set the connection on the command object
cmd.Connection = connection;
cmd.CommandText = "select salary from employees where employee_id = 109";
OracleDataReader reader = cmd.ExecuteReader();
// Don't forget to close your connection at some point
I purposely left out error checking and assuring the connection is closed after you use it. There is an example at the bottom of the following link that should help you out further.
https://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracleconnection(v=vs.110).aspx
Hope this helps and good luck!
In your code, you create a an object called con which is of type OracleConnection. But after setting the ConnectionString property, you never use this object. My guess is that you need to open the connection and somehow link the cmd object to this connection.

How can I get SQL result into a STRING variable?

I'm trying to get the SQL result in a C# string variable or string array. Is it possible? Do I need to use SqlDataReader in some way?
I'm very new to C# functions and all, used to work in PHP, so please give a working example if you can (If relevant I can already connect and access the database, insert and select.. I just don't know how to store the result in a string variable).
This isn't the single greatest example in history, as if you don't return any rows from the database you'll end up with an exception, but if you want to use a stored procedure from the database, rather than running a SELECT statement straight from your code, then this will allow you to return a string:
public string StringFromDatabase()
{
SqlConnection connection = null;
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Your Connection String Goes Here");
connection.Open();
var command = new SqlCommand("Your Stored Procedure Name Goes Here", connection)
{
CommandType = CommandType.StoredProcedure
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["Item"].ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
It can definitely be improved, but it would give you a starting point to work from if you want to go down a stored procedure route.
Try This:
SqlConnection con=new SqlConnection("/*connection string*/");
SqlCommand SelectCommand = new SqlCommand("SELECT email FROM table1", con);
SqlDataReader myreader;
con.Open();
myreader = SelectCommand.ExecuteReader();
List<String> lstEmails=new List<String>();
while (myreader.Read())
{
lstEmails.Add(myreader[0].ToString());
//strValue=myreader["email"].ToString();
//strValue=myreader.GetString(0);
}
con.Close();
accessing the Emails from list
lstEmails[0]->first email
lstEmails[1]->second email
...etc.,
You could use an SQL Data Reader:
string sql = "SELECT email FROM Table WHERE Field = #Parameter";
string variable;
using (var connection = new SqlConnection("Your Connection String"))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Parameter", someValue);
connection.Open();
using (var reader = command.ExecuteReader())
{
//Check the reader has data:
if (reader.Read())
{
variable = reader.GetString(reader.GetOrdinal("Column"));
}
// If you need to use all rows returned use a loop:
while (reader.Read())
{
// Do something
}
}
}
Or you could use SqlCommand.ExecuteScalar()
string sql = "SELECT email FROM Table WHERE Field = #Parameter";
string variable;
using (var connection = new SqlConnection("Your Connection String"))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Parameter", someValue);
connection.Open();
variable = (string)command.ExecuteScalar();
}
This May help you For MySQL
MySqlDataReader reader = mycommand.ExecuteReader();
while (reader.Read())
{
TextBox2.Text = reader.ToString();
}
For SQL
using (SqlCommand command = new SqlCommand("*SELECT QUERY HERE*", connection))
{
//
// Invoke ExecuteReader method.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
TextBox2.Text = reader.GetString(0);
}
}
Try this:
public string SaveStringSQL(string pQuery, string ConnectionString)
{
var connection = new Conexao(ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand(pQuery, connection.Connection);
var SavedString = (string)command.ExecuteScalar();
connection.Close();
return SavedString;
}
The ExecuteScalar function saves whatever type of data there is on your database - you just have to specify it.
Keep in mind that it can only save one line at a time.

connecting to sql database c# asp.net

hallo there
This is a very basic question. I am currently a student and have done ASP.NET with C#.
For our purposes it was required to do work with an access database where connecting to it and adding data etc.was very easy.
My feeling is that access is not used much in the real world and would just like to enquire on the easiest and most correct way of establishing a connection to Microsoft Sql Server Database(Transact sql).
In my case the database is called dbActivities with primary data file being dbActivitiesData.mdf.
OleDbDataConnection conn;
conn = new OleDbConnection = #"Provider=Microsoft.Jet.Oledb.4.0:"
#"Data Source=DataBase.mdb";
conn.Open();
Regards
My feeling is that access is not used much in the real world
Unfortunately Access is still very much used in the real world :-)
As far as the correct way is concerned I would recommend you wrapping the connection into a using block to ensure proper handling:
class Program
{
static void Main()
{
var connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\work\DataBase.mdb";
using (var conn = new OleDbConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
}
}
And as far as Microsoft SQL Server is concerned:
var connectionString = #"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
string strSQLCommand;
SqlCommand command;
SqlConnection conn = null;
conn =new SqlConnection("Data Source=serverName\IP;Initial Catalog=dbActivities;UID=User;PWD=Password;Max Pool Size=500;");
strSQLCommand = "Your Command";
command = new SqlCommand(strSQLCommand, conn);
command.ExecuteNonQuery();
conn.Close();

Categories