Trouble in executing the SQL query using c# - c#

using System;
using System.Data.SqlClient;
namespace ConsoleCSharp
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class DataReader_SQL
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
try
{
SqlConnection thisConnection = new SqlConnection(#"Network Library=dbmssocn;Data
Source=sourcename,1655;database=Oracle;User id=sysadm;Password=password;");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT * FROM SYSADM.PS_RQ_DEFECT_NOTE where ROW_ADDED_OPRID = 'github'";
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
Console.WriteLine(thisCommand.CommandText);
Console.ReadKey();
}
thisReader.Close();
thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
}
}
Please help me to resolve this issue.Thanks. I want to execute SQL query using c# and get the results on console.I guess there is some problem with my code.Please review and let me know the inputs.

If you want to print the query data, you should run a command like this:
Console.WriteLine(thisReader["ROW_ADDED_OPRID"].ToString());
..inside the while loop.

It appears that you're trying to use the SQL Native Client (normally for use for connecting to Microsoft SQL Server) rather than using an Oracle client. Whilst the System.Data.OracleClient namespace does exist, it is deprecated. Instead, you may want to consider connecting using an OleDbConnection with the appropriate connection string, so something like:
using (OleDbConnection con = new OleDbConnection(#"Network Library=dbmssocn;Data Source=sourcename,1655;database=Oracle;User id=sysadm;Password=password;")
{
con.Open();
using (OleDbCommand cmd = con.CreateCommand() )
{
cmd.CommandText = "SELECT * FROM SYSADM.PS_RQ_DEFECT_NOTE where ROW_ADDED_OPRID = 'github'";
using(IDataReader thisReader = cmd.ExecuteReader() )
{
while (thisReader.Read())
{
Console.WriteLine(thisReader["fieldname"]);
Console.ReadKey();
}
}
};
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Related

How to connect to InterBase database using c#

I have a need to connect to a report Interbase server and pull data from a table.
I have the following code, I am trying several options to make a successful connection to the server, however not able to do so. Could you please let me know what's wrong with my code. Or please point me to any article which shows a step by step approach to successfully connect to an Interbase server and pull data.
using System;
using System.Data;
using System.Data.Common;
using InterBaseSql.Data.InterBaseClient;
string connectionString = "server=remoteserver_ip_address;dataBase=C:\\test\\interbasedb\\database.gdb;User_Name=myusername;Password=mypassword;";
using (var connection = new IBConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var command = new IBCommand("select * from table rows 1", connection, transaction))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
Console.WriteLine(string.Join("|", values));
}
}
}
}
}
I suspect the issue is with the connection string. I tried changing the connection string several ways, but getting different error every time.
All errors below.
Client library - ibclient64 not found (I copied ibclient64.dll into the project folder, and this error was resolved)
Your user name and password are not defined. Ask your database administrator to set up a InterBase login.
connection rejected by remote interface
Unable to complete network request to host "remoteserver_ip_address". Failed to locate host machine. Undefined service gds_db/tcp.
I am able to connect to the same server using IBConsole application, Which I believe is a client software to connect to Interbase server (Like Management Studio for SQL Server, and WorkBench for MySQL and PGAdmin for PostgresSQL)
The Parameters I am using to connect to the Interbase Server using IBConsole are same as that of I am using in the C# code.
Report Server IP: remoteserver_ip_address
DataBase: C:\test\interbasedb\database.gdb
User Name: myusername
Password: mypassword
Partial breakthrough for above issue.
After several hours of trial and error, I was finally able to connect to the interbase server successfully using Embarcadero drivers.
I had to change the connectionstring to look as below for a successful connection.
server=remoteserver_ip_address;database=C:\test\interbasedb\database.gdb;user=myusername;password=mypassword
But now I am stuck with another issue. When I use a query like select * from some_table_which_doesnot_exists, I clearly receive a message that the Table is not found.
And when I use a query like Select * from a table_that_exists_in_the_db, I always get follow error.
Dynamic SQL Error
SQL error code - 804
SQLDA error (I believe SQLDA = SQL DataAdapter, because thats where the code it throwing error)
I went to the Embarcadero Error Codes List to see more information on this error and found the reason to be SQLDA missing or incorrect version, or incorrect number/type of variables.. I am stuck here not sure how to proceed further. Please help.
I think you are missing "PORT" details for connection to the interbase server instance.
You can try the below solution for the connection string. This has worked for me in my local machine.
static void Main(string[] args)
{
var cs = BuildConnectionStringBuilder().ToString();
try
{
using (var connection = new IBConnection(cs))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var command = new IBCommand("select * from employee rows 1", connection, transaction))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
Console.WriteLine(string.Join("|", values));
}
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private static IBConnectionStringBuilder BuildConnectionStringBuilder()
{
var builder = new IBConnectionStringBuilder();
builder.UserID = "SYSDBA";
builder.Password = "masterkey";
builder.DataSource = "localhost";
builder.Database = AppDomain.CurrentDomain.BaseDirectory + "test-employee.ib";
builder.Port = 3050;
return builder;
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1_3grupa
{
public partial class Form1 : Form
{
SqlConnection konekcija = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void buttonIzadji_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
string sqlUpit = "select * from Citalac";
try
{
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
SqlDataAdapter da = new SqlDataAdapter(komanda);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
ListViewItem listItem = new ListViewItem(row["HotelID"].ToString());
listItem.SubItems.Add(row["Naziv"].ToString());
listItem.SubItems.Add(row["Adresa"].ToString());
listItem.SubItems.Add(row["Telefon"].ToString());
listItem.SubItems.Add(row["Grad"].ToString());
listView1.Items.Add(listItem); // Dodaje red u ListView
}
}
catch (Exception)
{
//MessageBox.Show("Greska");
}
}
private void buttonPrikazDGV_Click(object sender, EventArgs e)
{
SqlParameter param = new SqlParameter();
param.ParameterName = "#param1";
param.Value = numericUpDown1.Value;
string sqlUpit = "select * from Hotel where HotelID=#param1";
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
komanda.Parameters.Add(param);
try
{
konekcija.Open();
SqlDataReader dr = komanda.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView2.DataSource = dt;
}
catch (Exception)
{
MessageBox.Show("Greska");
}
finally
{
konekcija.Close();
}
}
private void buttonPrikazLV_Click(object sender, EventArgs e)
{
string sqlUpit = "select * from Hotel";
try
{
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
SqlDataAdapter da = new SqlDataAdapter(komanda);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
ListViewItem listItem = new ListViewItem(row["HotelID"].ToString());
listItem.SubItems.Add(row["Naziv"].ToString());
listItem.SubItems.Add(row["Adresa"].ToString());
listItem.SubItems.Add(row["Telefon"].ToString());
listItem.SubItems.Add(row["Grad"].ToString());
listItem.SubItems.Add(row["Drzava"].ToString());
listItem.SubItems.Add(row["Kategorija"].ToString());
listView1.Items.Add(listItem); // Dodaje red u ListView
}
}
catch (Exception)
{
MessageBox.Show("Greska");
}
}
private void buttonIzadji2_Click(object sender, EventArgs e)
{
this.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

c# Query sqlite database, get back a data with a type

I am encountering some issues when it comes to getting back data from my c# database query
this is my code for the query :
using System;
using System.Text;
using System.Data;
using System.Data.SQLite;
namespace Cryptomoney
{
class DataClass
{
private static SQLiteConnection sqlite;
public DataClass()
{
sqlite = new SQLiteConnection("Data Source= DataCrypto.sqlite3;Version=3;New=False;");
}
public SQLiteDataReader SelectQuery(string query)
{
try
{
sqlite.Open(); //Initiate connection to the db
SQLiteCommand sqlComm = sqlite.CreateCommand();
sqlComm.CommandText = query;
SQLiteDataReader r = sqlComm.ExecuteReader();
sqlite.Close();
}
catch (SQLiteException ex)
{
Console.WriteLine(ex);
}
sqlite.Close();
return r;
}
}
}
and this is the code with the sql :
var b = dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1");
I want b to be a float, the same type as PercChange1h is in my database but I only get "System.Data.SQLite.SQLiteDataReader".
I already tried :
var b = (float)dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1")["PercChange1h"]
which returns an error "row does not exist". And all other types of casts do not work ((int), ToString())
My code is nearly the same with create or ALTER or INSERT and it works just fine (but I do not have to get back data"
var cmd = new SQLiteCommand();
cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
cmd.ExecuteNonQuery();
Do you know how I could get back a type like string or float from my sqlite db with c# ?
(this is my first question ever so if there is not enough data, I am here to answer)
Have a nice day!
Your function should look like this
public object QueryScalarValue(string query)
{
try
{
sqlite.Open(); //Initiate connection to the db
using(SQLiteCommand sqlComm = new SQLiteCommand(query, sqlite))
return sqlComm.ExecuteScalar();
}
catch (SQLiteException ex)
{
Console.WriteLine(ex);
}
finally
{
sqlite.Close();
}
return r;
}
Then you simply cast the result
var b = (double)dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1");

Is there a better way to connect my DB to my Form?

I'm trying to connect my DB to my ListView, and I'm trying to find a better way than what's in the book. I looked at a couple forums and a lot of them have the same thing like what's in my code down below.
We didn't have a lot of time to go over databases in class, so a lot of my knowledge with connection strings come from the internet and a small chapter in the book.My Database name is GameStoreLibrary.
using System.Data;
using System.Data.SqlServerCe;
public partial class DisplayGameStoreTable : Form
{
//WHAT THE C# FORUMS SAY TO DO
public SqlCeConnection cn = new SqlCeConnection(#"
Data Source=.;
Initial Catalog=DB GameStoreLibrary;
Integrated Security=True;
MultipleActiveResultSets=True");
private void DisplayGameStoreTable_Load(object sender, EventArgs e)
{
try
{
cn.Open();
}
catch(SqlCeException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
private void NewGameBttn_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM newGames ORDER BY gametitle ASC", cn);
try
{
SqlCeDataAdapter da = new SqlCeDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["gametitle"].ToString());
item.SubItems.Add(dr["releasedate"].ToString());
item.SubItems.Add(dr["console"].ToString());
item.SubItems.Add(dr["company"].ToString());
item.SubItems.Add(dr["gameprice"].ToString());
item.SubItems.Add(dr["quantity"].ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Small Tip :
Try to use a DBConnect class instead of typing connection string every single time and closing the connection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace InventoryManagementSystem
{
class DBConnect : IDisposable
{
private static String connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Private\InventoryManagementSystem\InventoryManagementSystem\InventoryDB.mdf;Integrated Security=True";
public SqlConnection con = new SqlConnection(connectionString);
public DBConnect()
{
try
{
con.Open();
Console.WriteLine("Database connected");
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine("Database Connection Failed");
throw new Exception();
}
}
public void Dispose()
{
con.Close();
}
}
}
After you have this in your project you just have to create an object whenever you want to access the database.
public void getData(){
using(DBConnect db = new DBConnect()){
String q = "select * from TestTable";
SqlCommand cmd = new SqlCommand(q,db.con);
SqlDatareader r = cmd.ExcecuteReader();
}
}
This will automatically close the connections too.
To add on to Gihan's answer, it's also an accepted practice to create the App.Config file and put the connection string in there so it's not inside your source code. Then it's easier to change without recompiling anything.
Use the ConnectionStrings section of the App.Config and then you can get the connection string using the code:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

how to convert all tables from SDF file together to csv file in c# or any application which converts

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlServerCe;
namespace ExportSDF
{
class Program
{
static void Main(string[] args)
{
SqlCeConnection conn = null;
SqlCeCommand cmd = null;
SqlCeDataReader rdr = null;
try
{
conn = new SqlCeConnection(#"Data Source = C:\Program Files\Microsoft SQL Server Compact Edition\v3.1\SDK\Samples\Northwind.sdf;max database size=256");
conn.Open();
cmd = new SqlCeCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader();
System.IO.TextWriter stm = new System.IO.StreamWriter(new System.IO.FileStream(#"C:\customers.csv", System.IO.FileMode.Create), Encoding.Default);
while (rdr.Read())
{
for (int i = 0; i < rdr.FieldCount-2; i++)
{
if (rdr[i] != null)
{
stm.Write(rdr[i].ToString());
stm.Write(";");
}
else
{
stm.Write(";");
}
}
if (rdr[rdr.FieldCount-1] != null)
{
stm.Write(rdr[0].ToString());
}
stm.Write(System.Environment.NewLine);
}
stm.Close();
rdr.Close();
cmd.Dispose();
}
finally
{
// Close the connection when no longer needed
//
conn.Close();
}
}
}
}
this program is not working please help me with a code or application which converts all the table together to csv file.i have some application which converts only one table at a time.i cannot select multiple table.
From what I can see, you got the code from here.
Could you please be clear on what does not work? What have you tried so far?
It seems to me that you only copied the code but didn't change the Data Source, which obviously won't work for you.
Thanks.

Getting a connection to database lost error

every once and a while my application throws a connection to database lost error.
The database class I got from a tutorial site and is below, it works great except for the above error sometimes, im guessing its timing out, like if the person using it goes for a smoke break and comes back and tries to continue where they left off.
And of coarse being the normal end-user they close then error message THEN come get me to tell me they got an error.
But until the error comes up again i thought i would ask what part of this code could be changed to prevent that error
this is a firebird db server and a c# application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows.Forms;
using FirebirdSql.Data.FirebirdClient;
namespace _0912111
{
class DatabaseConnection
{
private FbConnection conn;
private FbCommand sqlCommand;
private FbDataAdapter DB;
private DataSet DS = new DataSet();
public DatabaseConnection()
{
conn = new FbConnection("User=myuser;" + "Password=mypw;" + "Database=dbpath;" + "DataSource=serverip;" + "Port=dbport;" + "Dialect=3;" + "Charset=UTF8;");
}
public void showDbError(string theError)
{
MessageBox.Show("Could not connect to database\n\nError Details:\n" + theError);
}
public FbConnection Openconn()
{
if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken)
{
try
{
conn.Open();
}
catch (Exception e)
{
showDbError(e.Message.ToString());
}
}
return conn;
}
public FbConnection Closeconn()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
return conn;
}
public void nonQuery(string txtQuery)
{
FbCommand cmd = new FbCommand(txtQuery);
try
{
cmd.Connection = Openconn();
cmd.ExecuteNonQuery();
}
catch (Exception Ex)
{
showDbError(Ex.Message.ToString());
throw Ex;
}
finally
{
cmd = null;
}
}
public FbDataReader returnDataReader(string txtQuery)
{
FbCommand cmd = new FbCommand();
try
{
cmd.Connection = Openconn();
cmd.CommandText = txtQuery;
FbDataReader rd;
rd = cmd.ExecuteReader();
return rd;
}
catch (Exception Ex)
{
showDbError(Ex.Message.ToString());
throw Ex;
}
finally
{
cmd = null;
}
}
}
}
I would think that the code in her that says
if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken)
{
would prevent it??
Look, I suggest you to use using and rewrite your methods in a cleaner way, no reason to have another method to open and another to close connection, I'm not doing it anymore since longer than 5 years :D
also, no reason to do a ToString() on Ex.Message and also, notice, in C# you should throw exceptions with only throw not throw exc.
one of your methods would become this for example:
public void nonQuery(string txtQuery)
{
using(var conn = new FbConnection(GetMyConnectionString(...parameters...)))
{
using(var cmd = new FbCommand(txtQuery))
{
try
{
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
showDbError(ex.Message);
throw;
}
}
}
}
I'm 100% with Davide Piras on this. (upvoted him)
Delete the "Openconn" and "Closeconn" methods from your DatabaseConnection class. Then change your queries to have using statements for the connection open and command execution.
The database drivers already know how to perform connection pooling. Maintaining an open connection in code is not just a waste of time, but a potential cause of issues like the one you are experiencing. Other issues it can cause are leaked memory and the ability to open further connections with the database server.
So, rewrite your code to use best practices for database access and the problem will go away.
I'll leave this example that speaks of the connection and some examples that I hope will help.
http://code.msdn.microsoft.com/Esempio-applicazione-dati-494c129a
Regards.

Categories

Resources