Firebird SqlConnection - sql

I have problem with connecting to firebird tables. I tried every connection string i could find on internet but it doesn't work. Problem comes when i open connection
Here is code
private void RutinskiPopis_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"User ID=sysdba;Password=masterkey;Database=localhost:D:\\TDWORK.FDB;Data Source=localhost;");
SqlCommand cmd = new SqlCommand("SELECT Opis, Broj FROM PLNAZIVI", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1_Data((IDataRecord)dr);
}
con.Close();
}
Can anyone help me with that connection string?
Here is full connection string
initial catalog=D:\TDWORK.FDB;data source=localhost;user id=SYSDBA;role=admin

The problem is that you are using SqlConnection, which can only connect to Microsoft SQL Server. For Firebird you need to use FbConnection.
See for examples: .NET - examples of use.

I solved this by using FbConnection instead of SqlConnection, and then using standard firebird connection string.

Related

In a `SqlCommand`, what timespan does the `CommandTimeout` actually represent?

I am querying a Microsoft SQL Database using the SqlConnection, SqlCommand and SqlReader, much like described in https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader
Now, an SqlCommand allows to set the CommandTimeout, and I am doing it like so (simplified):
using (SqlConnection connection = GetConnection()) {
connection.Open();
using (SqlCommand command = connection.CreateCommand()) {
command.CommandText = query; //My custom SQL query
command.CommandType = CommandType.Text;
//Set Timeout
command.CommandTimeout = timeout.Value; //My custom timeout
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
//Read row by row and do stuff
}
}
}
}
My question is, to what does the Timeout actually apply to? Is it
The time spent in ExecuteReader()
The time spent in Read()
both of those
something else?
There seems no documentation of this specifically, neither in MSDN nor on the web.
It will apply to the time executing the command against the database which is command.ExecuteReader() which is complete by the time you start reading the records. You could test that by putting a break point in after that on the while and and sitting there - you won't hit your timeout.

How to extract and update data from Azure SQL DB from Azure functions

So I have this Azure function that works, and an Azure SQL DB with some data. But I cannot find a decent example to get data from the DB into the function. Surely, crafting a query string and SQLCommand.BeginExecuteReader/EndExecuteReader is not the preferred way, right?
LINQtoSQL perhaps?
Thanks, Bezz
You are free to use any .NET Data Access library that's available for other types of applications: ADO.NET, Entity Framework, Dapper etc.
A simple example:
Use Azure Functions to connect to an Azure SQL Database.
Apparently, it was quite simple. This code did the trick. Although I'm not completely happy with the fact that I'm crafting a query string. For now, it will do.
#r "System.Configuration"
#r "System.Data"
using System.Configuration;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
var str = ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString;
var caterers = new List<string>();
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Caterers";
cmd.Connection = conn;
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
caterers.Add(reader.GetString(1));
}
}
conn.Close();
}
return req.CreateResponse(HttpStatusCode.OK, caterers);
}

LogIn form, SQL exception

I'm trying to make a simple program that has a log-in part, with a local database just for testing.And i keep getting an error when I try to open the connection to the SQL database.
private void logInButton_Click(object sender, EventArgs e)
{
MainMenu openMainMenu = new MainMenu();
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30");
sqlcon.Open();
SqlCommand cmd = new SqlCommand("Select * from Table Where username ='" + usernameTextBox.Text + "' and password = '" + passwrodTextBox.Text + "'");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count > 0)
{
openMainMenu.Show();
this.Hide();
}
else
MessageBox.Show("Wrong username or password!");
}
I get the error at sqlcon.Open();, and it is: "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: An attempt to attach an auto-named database for file C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
Well, the best advice I can give you is to google the error message. Keep in mind that if there is an error message it means that the problem is well known an as such it's a safe bet that someone have encountered it before you and managed to solve it. The first 4 results of this search are on stackoverflow and at least two of them have accepted answers, so I believe a little reasearch would have saved you a long time.
This is the best advice because it streaches far beyond your current problem. I firmly believe that good searching skills is the most important and most powerfull tools of a sotfware developer. I can assure you, no matter how much time you are developing software, almost every exception you get, someone else have already solved and posted the solution somewhere, you only need to find it.
Now, as for the code it self - You have some major problems other then the exception you are asking about:
Concatenating strings into sql statements instead of using parameters expose your code to SQL injection attacks. This is a very serious threat that is extremely easy to fix.
Using insntances of classes that implements the IDisposable interface without properly disposing them may lead to memory leak. Read about the using statement and make it a habit to use it every time it's possible.
Exception handling. Currently, if your database can't be reached, you get an exception and your program crash. You should use a try...catch block anywhere you can't control in code to let your program end gracefuly instead. (Don't ever use try...catch for things you can do in code such as validate user input or checking division by zero - only for things that are beyon your control such as database availability.)
Having said all that, your code should look something like this:
private void logInButton_Click(object sender, EventArgs e)
{
using (var sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|C:\Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30"))
{
sqlcon.Open();
using (var cmd = new SqlCommand("Select 1 from Table Where username = #userName and password = #password"))
{
cmd.Parameters.Add("#userName", SqlDbType.NVarChar).Value = usernameTextBox.Text;
cmd.Parameters.Add("#password", SqlDbType.NVarChar).Value = passwrodTextBox.Text;
using (var dtbl = new DataTable())
{
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
var openMainMenu = new MainMenu();
openMainMenu.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Wrong username or password!");
}
}
}

Cannot access existing table from WCF Code

try
{
string strSQLConnString = GetConnectionString();
using (SqlConnection myConnection = new SqlConnection(strSQLConnString))
{
SqlCommand myCommand = new SqlCommand("spFortesting", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Param1", varParam1);
myCommand.Parameters.AddWithValue("#Param2", varParam2);
myCommand.Parameters.AddWithValue("#Param3", varParam3);
myCommand.Parameters.AddWithValue("#Param4", varParam4);
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
dt = new DataTable();
if (myReader.HasRows)
{
dt.Load(myReader);
}
myReader.Close();
}
myConnection.Close();
}
}
catch (Exception ex)
{
throw ex;
}
I am getting exception like
"The exception message is 'Could not find stored procedure 'spFortesting'."
All other existing Stored Procs are accessed correctly.
Connection string is common for all other SQL calls in the application.
'spFortesting' is newly created StoredProc.
owner is 'dbo' I tried with dbo.spname as well
While I can access the Stored Proc and Tables which are newly created using SQL Mgmt Studio and the same credentials as in web.config, but not thru the code.
What could have been wrong.
Thanks in Advance,
Amit
My mistake! when i watched it very closely I found that connection strings are not matching, the connectionstring was being picked up from the other similar sounding virtual directory. System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(#"\AppName");
and my appname on the deployed server was AppNameNew for some unkown reasons, since ages. With the name AppName there was another virtual folder and its web.config was pointing towards different database.
Sorry for the inconvenience caused if any.
Cheers!!!
and a Happy new year

can't connect to sql azure database using monotouch

I'm working on a iphone project using c# and monotouch.
I need to use an SQL Azure database.
My problem is that I cant seem to get connected using monotouch.
I can make the code below work fine in a native console application built on a windows 8 machine using visual studio 2012.
But, when I try to port it over to an imac and use monodevelop/monotouch my iphone app crashes.
The error I get is:
System.NotImplementedException: SSL encryption for data sent between client and server is not implemented.
I google around a bit and found a bug report that seems to describe my exact issue here. I noticed its almost two years old so i'm not sure if this would still be unimplemented.
So, I tried changing the value of StringBuilder.Encrypt = true; to false.
But, it still crashes and I get the error:
Mono.Data.Tds.Protocol.TdsInternalException: Server closed the connection. ---> System.IO.IOException: Connection lost
in either case the app crashes when conn.Open(); is called.
I'm pretty stuck, and I don't have a choice but to use SQL Azure.
So, if anyone could suggest a solution or work around for my issue, I'd appreciate it greatly.
thanks in advance!
string userName = "<username>#<myservername>";
string password = "<password>";
string dataSource = "<myservername>.database.windows.net";
string databaseName = "<dbname>";
SqlConnectionStringBuilder connStringBuilder;
connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = dataSource;
connStringBuilder.InitialCatalog = databaseName;
connStringBuilder.Encrypt = true;
connStringBuilder.TrustServerCertificate = false;
connStringBuilder.UserID = userName;
connStringBuilder.Password = password;
using (SqlConnection conn = new SqlConnection (connStringBuilder.ToString())) {
conn.Open();
using (IDbCommand dbcmd = conn.CreateCommand()){
string sql = "Select client_username from dbo.client;";
dbcmd.CommandText = sql;
using (IDataReader reader = dbcmd.ExecuteReader()){
while( reader.Read() ){
string username = (string) reader["client_username"];
}
}
}
}
SSL for SqlConnection class is not implemented. See SqlConnection.cs
And as Azure requires an encrypted connection you'll have to do some workaround. For example you could create a web role and expose a web service which executes the SQL on your behalf.
try using a simple string as your connection string:
connStr = "Server=tcp:<server_here>.database.windows.net,1433;Database=<db_name_here>;Trusted_Connection=False;Encrypt=True;TrustServerCertificate=False;UserID=<user_name_here>#<server_name_here>;Password=<password_here>";
using (SqlConnection conn = new SqlConnection (connStr)) {
conn.Open();
using (IDbCommand dbcmd = conn.CreateCommand()){
string sql = "Select client_username from dbo.client;";
dbcmd.CommandText = sql;
using (IDataReader reader = dbcmd.ExecuteReader()){
while( reader.Read() ){
string username = (string) reader["client_username"];
}
}
}
}
Note differences - use Server, Database. Once you get the connection string correct, you can use try the ConnectionStringBuilder and see if you get the exact same output. BUt its easier to just use a string if you have one that works.