Can't connect to postrgres using Visual Studio with dotConnect - c#

When I try to connect to DataBase, I get error: Key word doesn't support: Host.
int x = Int32.Parse(textBox1.Text);
try
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString =
Properties.Settings.Default.postgresConnectionString;
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "getCount";
System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter("#k",
SqlDbType.Int);
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#Tovar", x));
con.Open();
cmd.ExecuteNonQuery();
string kolvo = cmd.Parameters["#k"].Value.ToString();
con.Close();
label1.Text = kolvo + " израсходован в количестве ";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Connection String:
User Id=postgres;Password=8loz9fnl;Host=localhost;Database=postgres;Persist Security Info=True

I guess that you're using devart's dotconnect for ado.net connectivity so you should import Devart.Data.PostgreSql and use PgSqlConnection instead of sqlconnection and pgsqlcommand instead of sqlcommand

As others have mentioned already, you need to use Npgsql. Also use imports to simplify your code. Example connection code:
import the assembly using Npgsql; then to get a connection and open it
using (var conn = new NpgsqlConnection(Properties.Settings.Default.postgresConnectionString))
{
// you other code here
}
This way your resources are managed automatically and you don't need to call the close method, also you need to change the type of command as #wingedpanther mentions. Reading a good tutorial or the docs mentioned will help a lot.
Also you need to fix your connection string as:
Server=localhost;User Id=postgres;Password=8loz9fnl;Database=postgres;Persist Security Info=True
And avoid putting your actual username and password.

Related

SQL query "Data type mismatch in criteria expression."

I'm working on Form that sends about 9 fields to my SQL ACCESS database and i got this error.
"Data type mismatch in criteria expression."
i'm sure it's something with the ' x ' i put in my query but still can't figure out what is THE problem.
it's (int,int,string,string,string,int,int,string,int,int) format
string SqlStr = string.Format("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values({0},{1},'{2}','{3}','{4}',{5},{6},'{7}',{8},{9})", s.ClientId,s.OrderId,s.Date,s.CardTyp,s.PayMethod,s.Ex_Y,s.Ex_M,s.CcComp,s.CcNum,s.TotalSale);
Thanks for your help.
String.Format will not be a good approach for building queries. I suggest you to use, Parameterised queries that helps you to specify the type too and also its more helpful to prevent injection: Here is an example for you:
string query = "insert into Orders" +
"(client_id,order_id,date_,card_typ,...)" +
" values(#client_id,#order_id,#date_,#card_typ...)";
using (SqlCommand sqCmd = new SqlCommand(query, con))
{
con.Open();
sqCmd.Parameters.Add("#client_id", SqlDbType.Int).Value = s.ClientId;
sqCmd.Parameters.Add("#order_id", SqlDbType.VarChar).Value = s.OrderId;
sqCmd.Parameters.Add("#date_", SqlDbType.DateTime).Value = s.Date;
sqCmd.Parameters.Add("#card_typ", SqlDbType.Bit).Value = s.CardTyp;
// add rest of parameters
//Execute the commands here
}
Note: I have included only few columns in the example, you can replace ... with rest of columns.
Please dont use a concatenation string ...
Here is an example :
using (SqlConnection connection = new SqlConnection("...connection string ..."))
{
SqlCommand command = new SqlCommand("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values(#client_id,#order_id,#date_,#card_typ,#pay_mthd,#ex_y,#ex_m,#cc_comp,#cc_num,#t_sale)", connection);
SqlParameter pclient_id = new SqlParameter("#client_id", System.Data.SqlDbType.Int);
pclient_id.Value = 12;
command.Parameters.Add(pclient_id);
SqlParameter pcard_typ = new SqlParameter("#card_typ", System.Data.SqlDbType.VarChar);
pcard_typ.Value = "some value";
command.Parameters.Add(pcard_typ);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}

How to actually execute a command?

I'm playing around making a POC and I've created the following call.
public string DoStuff()
{
try
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlConnection connection = new SqlConnection("Server...");
string command = "insert into Records values (...)";
adapter.InsertCommand = new SqlCommand(command, connection);
}
}
catch (Exception exception)
{
return exception.Message + " " + exception.InnerException;
}
return "WeeHee!";
}
The text I'm seeing returned is the happy one, so I conclude there's no exceptions. Hence, I conclude that the call to the DB is performed as supposed to. However, there's no new lines in the DB being created.
I'm using the same connection string as I have in my config file and the command in pasted in from SQL Manager, where it works.
So my suspicion was that although I create an insert command, I never actually execute it but according to MSDN that's how it's supposed to work.
What stupid thing do I miss here?
You are missing connection.Open(); and adapter.InsertCommand.ExecuteNonQuery();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlConnection connection = new SqlConnection("Server...");
connection.Open();
string command = "insert into Records values (...)";
adapter.InsertCommand = new SqlCommand(command, connection);
adapter.InsertCommand.ExecuteNonQuery();
}
You should use ExecuteNonQuery instead. Using an SqlDataAdapter for an INSERT query does not make sense.
Also you should Open your connection just before you execute it.
You can:
using(SqlConnection connection = new SqlConnection("Server..."))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "insert into Records values (...)";
connection.Open();
int craeted = command.ExecuteNonQuery();
}
The example you linked to returned a SQLAdapter for later use.
You don't need one at all:
using (SqlConnection connection = new SqlConnection("Server..."))
{
string command = "insert into Records values (...)";
connection.Open();
var command = new SqlCommand(command, connection);
command.ExecuteNonQuery();
}
Note that there are other execution methods, depending on expected return values and whether you want asynchronous operation: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

Connect to remote oracle database using odac

I need to make asmx web service. I installed ODAC from here
Then, i add references to my project:
1) Oracle.DataAccess
2) Oracle.Web
[WebMethod]
public string EaaTest(string r_object_id)
{
string connString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)" +
"(HOST=my host)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=dcmt)));" +
"User Id=my id ;Password=my password;"
using (OracleConnection conn = new OracleConnection(connString))
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = string.Format("select DSS_TITLE_RU from DBREP36.DDT_DA_DIRECTION_S where R_OBJECT_ID=0", r_object_id);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
string result = dr.GetString(0);
return result;
}
}
Now, i have exception:
An exception of type 'System.InvalidOperationException' occurred in
Oracle.DataAccess.dll but was not handled in user code
Additional information: Connection must be open for this operation
On line: OracleDataReader dr = cmd.ExecuteReader();
Error message isn't clear at all?
Connection must be open for this operation
You need to open your connection before you execute your command.
conn.Open();
OracleDataReader dr = cmd.ExecuteReader();
Use using statement to dispose your command and reader as you did for your connection.
By the way, you didn't specify zero index in your string.Format. Your
where R_OBJECT_ID=0
should be
where R_OBJECT_ID = {0}
As a better option, use parameterized queries. Any kind of string concatenations are open for SQL Injection attacks.
Since you return just first column of the first row, use ExecuteScalar instead which is exactly what this for.
using(var conn = new OracleConnection(connString))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = #"select DSS_TITLE_RU from DBREP36.DDT_DA_DIRECTION_S
where R_OBJECT_ID = #id";
cmd.Parameters.AddWithValue(#id, r_object_id);
conn.Open();
return (string)cmd.ExecuteScalar();
}

C# and sql server

I've created a database and a table with 2 fields Id and Name.
Now I want to insert values on clicking a button the sammple code is given. it's not working.
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command =new SqlCommand("insert into Test (Id,Name) values(5,kk);",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
String values should be in quotes. This has not much to do with C#, more with T-SQL
Try this, and notice the kk;
SqlCommand command =
new SqlCommand("insert into Test (Id,Name) values(5,'kk');",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Also I am assuming here that Id is not an auto-increment field. If it is, then you should not fill it.
As a side-node you should look at parameterized queries to prevent SQL injection.
In this instance, you need single quotes ' around the kk
insert into Test (Id,Name) values(5,'kk')
In general, you should use parameterised queries
try this:
SqlConnection conn = new SqlConnection();
SqlTransaction trans = conn.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand("insert into Test (Id,Name) values(#iD, #Name)", conn, trans))
{
cmd.CommandType = CommandType.Text;
cmd.AddParameter(SqlDbType.UniqueIdentifier, ParameterDirection.Input, "#iD", ID);
cmd.AddParameter(SqlDbType.VarChar, ParameterDirection.Input, "#Name", Name);
cmd.ExecuteNonQuery();
}
conn.CommitTransaction(trans);
}
catch (Exception ex)
{
conn.RollbackTransaction(trans);
throw ex;
}
Try this:
SqlConnection con = new SqlConnection('connection string here');
string command = "INSERT INTO Test(Id, Name) VALUES(5, 'kk')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
String values should be between ' '
Verify your connection string
//add your connection string between ""
string connectionString = "";
using (var conn = new SqlConnection(connectionString))
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO pdf (Id, Name) VALUES (5, 'kk')";
conn.Open();
conn.ExecuteNonQuery();
conn.Close();
}
It looks like you have multiple problems with your current code.
You need to enclose string values in single quotes, as pointed out in other answers.
You need to enable remote connection to your SQL server.
Check the following link if you are using SQL server 2008.
How to enable remote connections in SQL Server 2008?
and for SQL Server 2005 see:
How to configure SQL Server 2005 to allow remote connections

Using a existing connection in a Script Component (SSIS)

I have am OLEDB Connection configured in the connection managers and I want to use it in a SCRIPT. The script needs to call a stored proc and then create buffer rows. I have added the connection to the connections available to the script and this is my code.
Boolean fireagain = true;
SqlConnection conn = new SqlConnection();
conn = (SqlConnection)(Connections.Connection
.AcquireConnection(null) as SqlConnection);
SqlCommand cmd = new SqlCommand();
conn.Open();
ComponentMetaData.FireInformation(
0, "Script", "Connection Open", string.Empty, 0, ref fireagain);
cmd.Connection = conn;
cmd.CommandText = "up_FullTextParser_select" ;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Phrase", DbType.String).Value = Row.Keywords;
cmd.Parameters.AddWithValue("SpecialTerm", DbType.String).Value = "Exact match";
cmd.Parameters.AddWithValue("StopListId", DbType.Int32).Value = 0;
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
TermsBuffer.AddRow();
TermsBuffer.Term = rdr[0].ToString();
}
conn.Close();
Anyway, it seems to fail on the AcquireConnection. Am I converting this wrong? Should I be using a different way to using the connections defined outside the script?.
You cannot cast an OLEDB connection to SqlConnection object. You must use the OleDbConnection object. See the example - http://blogs.msdn.com/b/mattm/archive/2008/08/22/accessing-oledb-connection-managers-in-a-script.aspx
This MSDN example implies that you using AcquireConnection incorrectly.
You need to use a managed connection provider.
If you insist on using an OLEDB connection, you cannot use AcquireConnection but you can extract the connection string and then use it to create an OLEDB connection:
string connstr = Dts.Connections["my_OLEDB_connection"].ConnectionString;
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(connstr);
This may not work if the connection string is created via an expression of some sort.
IDTSConnectionManager100 connMgr = this.Connections.ADONetAppStaging ; //this we need to give name in connection manager in script component
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(connMgr.AcquireConnection(null));
//Read data from table or view to data table
string query = "Select top 10 * From ##AP_Stagging_Temp_ExportWODuplicates Order by 1,2,3 asc ";
// string query = "Select * From ##AP_Stagging_Temp_For_JLL_ExportWODuplicates order by 1,2,3 asc ";
SqlDataAdapter adapter = new SqlDataAdapter(query, myADONETConnection);
datatable dtExcelData = new datatable();
adapter.Fill(dtExcelData);
myADONETConnection.Close();

Categories

Resources