Unable to connect to Postgre SQL data base - c#

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

Related

ADO.NET + T-SQL Invoke scalar function from another DB?

I have an SQL script select [master].[dbo].sp_SearchDuplicatedAddress('','','','') that I can invoke successfully from management studio. The function sp_SearchDuplicatedAddress exists in master database and is accessible by the logged user, no problem here. The problem arises when I try to execute that SQL script from ADO.Net I get the following error:
System.Data.SqlClient.SqlException: 'Cannot find either column "master" or the user-defined function or aggregate "master.dbo.sp_SearchDuplicatedAddress", or the name is ambiguous.'
And here's the code of sample app:
var conn = new SqlConnection();
var cmd = conn.CreateCommand();
cmd.CommandText = "select [master].[dbo].sp_SearchDuplicatedAddress('','','','')";
conn.Open();
var outt = cmd.ExecuteScalar();
}
Any idea how can I execute cross database queries from ADO.Net?
No repro for me. Can you modify the below to reproduce the behavior?
using Microsoft.Data.SqlClient;
using System;
namespace SqlClientTest
{
class Program
{
static void Main(string[] args)
{
var constr = "server=localhost;database=master;integrated security=true";
using (var conn = new SqlConnection(constr))
{
var cmd = conn.CreateCommand();
cmd.CommandText = #"
create or alter function dbo.sp_SearchDuplicatedAddress ( #a varchar(20),#b varchar(20),#c varchar(20),#d varchar(20) )
returns int
as
begin
return 3;
end ";
conn.Open();
cmd.ExecuteNonQuery();
}
constr = "server=localhost;database=tempdb;integrated security=true";
using (var conn = new SqlConnection(constr))
{
var cmd = conn.CreateCommand();
cmd.CommandText = "select [master].[dbo].sp_SearchDuplicatedAddress('','','','')";
conn.Open();
var outt = cmd.ExecuteScalar();
Console.WriteLine(outt);
}
}
}
}

Executing SQl Queries in C# using CLR

I am using SQl CLR for parsing some table column. I want to execute the queries also in C# user defined function. Can somebody give an example to execute select and insert queries in the function?
Thank you in advance.
SqlConnection objSqlConn;
string connString = string.Empty;
connString = "Data Source=(local);Initial Catalog=DB;User ID=uname;pwd=pass;Password=pass";
objSqlConn = new SqlConnection(connString);
objSqlConn.Open();
string query = "Select count(*) FROM [DB].[dbo].[TableName]";
SqlCommand cmdTotalCount = new SqlCommand(query, objSqlConn);
cmdTotalCount.CommandTimeout = 0;
string TotalCountValue = cmdTotalCount.ExecuteScalar().ToString();
return TotalCountValue;
In CLR, you can use existing connection to run queries.
Simple, returning data to client:
var cmd = new SqlCommand("select * from [table]");
SqlContext.Pipe.ExecuteAndSend(cmd);
Returning data via SqlDataReader:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("select * from table", con);
con.Open();
var rdr = cmd.ExecuteReader();
SqlContext.Pipe.Send(rdr);
rdr.Close();
con.Close();
Running other commands:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("insert into [table] values ('ahoj')", con);
con.Open();
var rsa = cmd.ExecuteNonQuery();
con.Close();
Once you switch to C# you execute queries like you'd normally do from your application (using ADO.NET's SqlConnection and SqlDataReader, using LINQ to SQL or using your custom build data layer).
To connect with the database you have to mention the database username and password in the connection string of your web.config file.

inserting and deleting not happening in local database (.sdf)

When I try to select values from a local database it executes without any issue. But when I try to insert and delete it's executing the query but it's not affecting any rows.
This is the code I'm using to delete row from my local database:
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = Database1.sdf";
SqlCeCommand cmd = sqlConnection1.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "DELETE FROM table1 WHERE slno=2";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.Prepare();
int aff=cmd.ExecuteNonQuery();//here its returning '0'
MessageBox.Show(aff.ToString());
sqlConnection1.Dispose();
sqlConnection1.Close();
It is possible that the delete won't affect any rows.
As an aside, I would advise using the using statement in your code:
using (SqlCeConnection conn = new SqlCeConnection("Data Source = Database1.sdf"))
using (SqlCeCommand comm = new SqlCeCommand("DELETE FROM table1 WHERE slno = 2", conn))
{
conn.Open();
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
This will handle disposal of relevant objects for you.
Assuming that the SQL is relevant to your database and that you have successfully connected using the connection string beforehand, then the above could will perform a delete action against your database.

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

How do I connect to a database and loop over a recordset in C#?

What's the simplest way to connect and query a database for a set of records in C#?
#Goyuix -- that's excellent for something written from memory.
tested it here -- found the connection wasn't opened. Otherwise very nice.
using System.Data.OleDb;
...
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";
using (OleDbCommand cmd = new OleDbCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Select * from yourTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Console.WriteLine(dr["columnName"]);
}
}
}
}
Very roughly and from memory since I don't have code on this laptop:
using (OleDBConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Whatever connection string";
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "Select * from CoolTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// do something like Console.WriteLine(dr["column name"] as String);
}
}
}
}
That's definitely a good way to do it. But you if you happen to be using a database that supports LINQ to SQL, it can be a lot more fun. It can look something like this:
MyDB db = new MyDB("Data Source=...");
var q = from db.MyTable
select c;
foreach (var c in q)
Console.WriteLine(c.MyField.ToString());
This is an alternative way (DataReader is faster than this one):
string s = "";
SqlConnection conn = new SqlConnection("Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 name, dbid FROM sysdatabases", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
s += dt.Rows[i]["name"].ToString() + " -- " + dt.Rows[i]["dbid"].ToString() + "\n";
}
MessageBox.Show(s);
If you are intending on reading a large number of columns or records it's also worth caching the ordinals and accessing the strongly-typed methods, e.g.
using (DbDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
int idxColumnName = dr.GetOrdinal("columnName");
int idxSomethingElse = dr.GetOrdinal("somethingElse");
do {
Console.WriteLine(dr.GetString(idxColumnName));
Console.WriteLine(dr.GetInt32(idxSomethingElse));
} while (dr.Read());
}
}
If you are querying a SQL Server database (Version 7 and up) you should replace the OleDb classes with corresponding classes in the System.Data.SqlClient namespace (SqlConnection, SqlCommand and SqlDataReader) as those classes have been optimized to work with SQL Server.
Another thing to note is that you should 'never' select all as this might lead to unexpected results later on if you add or remove columns to this table.
I guess, you can try entity framework.
using (SchoolDBEntities ctx = new SchoolDBEntities())
{
IList<Course> courseList = ctx.GetCoursesByStudentId(1).ToList<Course>();
//do something with courselist here
}
Charge the libraries
using MySql.Data.MySqlClient;
This is the connection:
public static MySqlConnection obtenerconexion()
{
string server = "Server";
string database = "Name_Database";
string Uid = "User";
string pwd = "Password";
MySqlConnection conect = new MySqlConnection("server = " + server + ";" + "database =" + database + ";" + "Uid =" + Uid + ";" + "pwd=" + pwd + ";");
try
{
conect.Open();
return conect;
}
catch (Exception)
{
MessageBox.Show("Error. Ask the administrator", "An error has occurred while trying to connect to the system", MessageBoxButtons.OK, MessageBoxIcon.Error);
return conect;
}
}

Categories