C# connection to oracle DB - c#

I am trying to get a select result and write a simple authentication. But i have some problems with reader.HasRows/table.Rows.Count>0, its always false. Maybe reason not in reader/adapter, but i dont have other ideas
Form1.cs[enter image description here][1]
private void button1_Click(object sender, EventArgs e)
{
String loginUser = loginField.Text;
String paswwordUser = passwordField.Text;
DB db = new DB();
DataTable table = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter();
OracleCommand command = new OracleCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * from users where login='#uL' AND pass = '#uP' ";
command.Parameters.Add("#uL", OracleDbType.Varchar2).Value = loginUser;
command.Parameters.Add("#uP", OracleDbType.Varchar2).Value = paswwordUser;
command.Connection = db.GetConnection();
db.openConnection();
// OracleDataReader reader = command.ExecuteReader();
adapter.SelectCommand = command;
table.Load(command.ExecuteReader());
adapter.Fill(table);
if (table.Rows.Count>0)
MessageBox.Show("Yes");
else
MessageBox.Show("No");
// reader.Close();
}
DB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client;
{
class DB
{
OracleConnection connection = new OracleConnection("Data Source=****/XEPDB1;User Id=****;Password=****;");
public void openConnection()
{
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
}
public void closeConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
connection.Close();
}
public OracleConnection GetConnection()
{
return connection;
}
}
}
https://i.stack.imgur.com/8m5ZZ.jpg

try to use colon:
command.CommandText = "SELECT * from users where login=:uL AND pass = :uP ";
command.Parameters.Add("uL", OracleDbType.Varchar2).Value = loginUser;
command.Parameters.Add("uP", OracleDbType.Varchar2).Value = paswwordUser;
command.Connection = db.GetConnection();
db.openConnection();
DataSet dataSet = new DataSet();
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(dataSet, "Users");
}
var dataTable= dataSet.Tables["Users"];
this.BindingContext[dataTable].EndCurrentEdit();
if(dataSet.HasChanges(DataRowState.Modified))
{
// do your stuff here
}

Related

How do I reset/reload/unload my DataGridView?

I have this problem while working on a problem on my assignment/homework. I wanted to load multiple data table from my SQL database into multiple datagridviews but when i click on another tab (with SelectedIndexChanged on TabControl) the column of the older loaded table still there. I just want each tab to show specific tables(columns).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace assignment2Database
{
public partial class Form1 : Form
{
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
string str = #"Data Source=DESKTOP-S1O2044\SQLEXPRESS;Initial Catalog=ElectroShopDB;Integrated Security=True";
private void tabSupplier_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl.SelectedIndex == 0)
{
connection = new SqlConnection(str);
connection.Open();
loadCatalogue();
}
else if (tabControl.SelectedIndex == 1)
{
connection = new SqlConnection(str);
connection.Open();
loadSupplier();
}
}
void loadCatalogue()
{
command = connection.CreateCommand();
command.CommandText = "select catalogueID,catalogueName from Catalogue";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvCatalogue.DataSource = table;
}
private void Form1_Load(object sender, EventArgs e)
{
connection = new SqlConnection(str);
connection.Open();
loadCatalogue();
}
void loadSupplier()
{
command = connection.CreateCommand();
command.CommandText = "select supplierID,supplierName from Supplier";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvSupplier.DataSource = table;
}
I want the SelectedIndexChanged event when triggered on each tabs on tab control to not have the old columns of the previous datagridview appear on the new loaded datagridview. Or I just want each individual datagridview to hold a table from my SQL database.
Unbind the first datasource and then rebind:
dgvSupplier.DataSource = null;
dgvSupplier.DataSource = table;
This will kick out all the older columns and only populate the ones you need. Do this in every method you use to repopulate your grid:
void loadCatalogue()
{
command = connection.CreateCommand();
command.CommandText = "select catalogueID,catalogueName from Catalogue";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvSupplier.DataSource = null;
dgvCatalogue.DataSource = table;
}
void loadSupplier()
{
command = connection.CreateCommand();
command.CommandText = "select supplierID,supplierName from Supplier";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvSupplier.DataSource = null;
dgvSupplier.DataSource = table;
}
Like so.
Edit:
Additionally, you can create a new adapter in your population methods to empty them:
void loadCatalogue()
{
SqlDataAdapter catalogueAdapter = new SqlDataAdapter();
command = connection.CreateCommand();
command.CommandText = "select catalogueID,catalogueName from Catalogue";
catalogueAdapter.SelectCommand = command;
table.Clear();
catalogueAdapter.Fill(table);
dgvSupplier.DataSource = null;
dgvCatalogue.DataSource = table;
}
void loadSupplier()
{
SqlDataAdapter supplierAdapter = new SqlDataAdapter();
command = connection.CreateCommand();
command.CommandText = "select supplierID,supplierName from Supplier";
supplierAdapter.SelectCommand = command;
table.Clear();
supplierAdapter.Fill(table);
dgvSupplier.DataSource = null;
dgvSupplier.DataSource = table;
}

Trying to pass SqlCommand in SqlDataAdapter as parameters

I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();
I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.
Running code (aspx page code)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = #USERNAME AND PASSWORD = #PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
Successful connection class code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
How can I pass CommandType.Text as parameters for SqlDataAdapter?
Error code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
I am getting this error:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
public DataTable SelectData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Your Connection String here"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
}
To use:
SelectData("select * from yourTable");
Reds has the answer. Just to clean the code up a little bit...
public DataTable SelectData(string query)
{
using (var connection = new SqlConnection("myConnectionString"))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
connection.Open();
adapter.Fill(dt);
return dt;
}
}
Actually you should pass the connection object on SQLCommand.Hope it helped you
DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.

Set datatables to be equivalent

This is probably a simple question but I am not experienced in C#.
I have 2 datatables, 1 is basically a copy of the other (like a table to review information). To set the values this is what I am doing now:
string attribute1 = "";
string attribute2 = "";
string attribute3 = "";
.....
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_id;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE parameter=#identifying_parameter", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
attribute1 = Convert.ToString(reader["attribute1"]);
attribute2 = Convert.ToString(reader["attribute2"]);
attribute3 = Convert.ToString(reader["attribute3"]);
.....
}
con.Close();
}
}
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO table2 (attribute1, attribute2, attribute3, ...) VALUES(#attribute1, #attribute2, #attribute3, ...)", con))
{
cmd.Parameters.AddWithValue("#attribute1", attribute1);
cmd.Parameters.AddWithValue("#attribute2", attribute2);
cmd.Parameters.AddWithValue("#attribute3", attribute3);
....
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
Obviously I might have a lot of attributes, so is there a simpler way to set every attribute in the table to be equal in C#?
You can use INSERT..INTO..SELECT
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO table2 (attribute1, attribute2, attribute3, ...)
SELECT attribute1, attribute2, attribute3 ... FROM table1
WHERE parameter=#identifying_parameter
", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
You can use * instead of specifying the column name, although which is not good practice..
In order to make a second Table identical (or "equivalent" as per your definition) to the first one (for certainty let's call it sourceTable), you can use SqlBulkCopy.WriteToServer Method (DataTable)(re: https://msdn.microsoft.com/en-us/library/ex21zs8x%28v=vs.110%29.aspx)
using (SqlConnection YourConnection= new SqlConnection(YourConnectionString))
{
YourConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(YourConnection))
{
bulkCopy.DestinationTableName = "dbo.YourDestinationTable";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(sourceTable);
}
catch (Exception ex) { }
}
}
In order to get a sourceTable you can use the following code snippet:
DataTable sourceTable = SqlReadDB(YourConnString, "SELECT *")
private static DataTable SqlReadDB(string ConnString, string SQL)
{
DataTable _dt;
try
{
using (SqlConnection _connSql = new SqlConnection(ConnString))
{
using (SqlCommand _commandl = new SqlCommand(SQL, _connSql))
{
_commandSql.CommandType = CommandType.Text;
_connSql.Open();
using (SqlCeDataReader _dataReaderSql = _commandSql.ExecuteReader(CommandBehavior.CloseConnection))
{
_dt = new DataTable();
_dt.Load(_dataReaderSqlCe);
_dataReaderSql.Close();
}
}
_connSqlCe.Close();
return _dt;
}
}
catch { return null; }
}
}
Hope this may help.

How to save data from local sdf database into text file?

Is there any possibility to save data from local sdf database into text file in C# ? I don't have any idea how to do it and unfortunettly I don't have a lot of time.. each row of the database must be in new line of text file
You must do it manually (i.e. by code). MS SQL CE does not provide the import/export features that the SQL Server editions do.
this is from an old project of mine it works. just change the name of the table "tableProduit" with the name of your choice. if you run into problems ask ....
using System;
using System.Data.SqlServerCe;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Data;
namespace app
{
class Connexion
{
SqlCeConnection conn;
string connectionString;
string chemin;
public Connexion(string path,string password)
{
this.chemin = path;
connectionString = string.Format("DataSource={0}", this.chemin + ";Password="+password);
conn = new SqlCeConnection(connectionString);
}
public bool isConnected()
{
try
{
conn.Open();
}catch(SqlCeException e){
MessageBox.Show(e.ToString());
return false;
}
bool temp = false;
SqlCeDataReader dr;
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tableProduit";
dr = cmd.ExecuteReader();
if (dr.Read())
{
temp = true;
}
else
{
temp = false;
}
dr.Close();
conn.Close();
return temp;
}
public void writeData(string filepath,string filetype)
{
conn.Open();
SqlCeDataReader dr;
SqlCeCommand cmd = new SqlCeCommand();
SqlCeDataAdapter adpt = new SqlCeDataAdapter();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tableProduit";
dr = cmd.ExecuteReader();
adpt.SelectCommand = cmd;
if (filetype == "txt")
{
TextWriter writer = new StreamWriter(filepath);
while (dr.Read())
{
writer.WriteLine(dr["codeBarre"] + ":" + dr["qte"]);
}
writer.Close();
}
else
{
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
adpt.Fill(dt);
ds.Tables.Add(dt);
}
dr.Close();
conn.Close();
}
}
}
Edit : forget about the fileds writer.WriteLine(dr["codeBarre"] + ":" + dr["qte"]); change them to the names of your fields.good luck

SQL Server connection in WPF

I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid. Connection is successfully created but when I show it in grid,it show db error(Exception handling).
This is what I am doing.Thanks in advance.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
It shows connected when i comment the line sda.Fill(dt);
Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
You don't assign the command any connection. You open the connection then create a command, but don't link the two.
Try something like:
SqlConnection conn = new SqlConnection(#"Server(local);Database=Sample_db;Trusted_Connection=Yes;");
conn.Open();
string sql= "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
Assign Connection Object to SqlCommand Object.
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandTimeout = 15;
command.CommandType = CommandType.Text;
command.CommandText = queryString;
connection.Open();
//Perfom desired Action
}
Add thisConnection as 2nd parameter in
Sqlcommand cmd = new SqlCommand(Get_Data, thisConnection)
try {
string connectionstring = "#"
Server = (local) Database = Sample_dbTrusted_Connection = Yes;
"";
SqlConnection thisConnection = new SqlConnection(connectionstring);
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data, thisConnection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);`
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
} catch {
MessageBox.Show("db error");
}
I use this code with Oracle and hope it will help you.
First add reference Oracle.DataAccess then add namespace using Oracle.DataAccess.Client;
And using the following code
try
{
string MyConString = "Data Source=localhost;User Id= yourusername;Password=yourpassword;";
using (OracleConnection connection = new OracleConnection(MyConString))
{
connection.Open();
sqldb1 = "select * from DEMO_CUSTOMERS;";
using (OracleCommand cmdSe1 = new OracleCommand(sqldb1, connection))
{
DataTable dt = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmdSe1);
da.Fill(dt);
db1.ItemsSource = dt.DefaultView;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
XAML code:
<DockPanel>
<DataGrid Margin="10.0" DockPanel.Dock="Left" Name="db1" AutoGenerateColumns="True" >
</DataGrid>
</DockPanel>
public DataTable Execute(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable dt = new DataTable();
sda.SelectCommand = command;
command.Connection = connection;
connection.Open();
sda.Fill(dt);
connection.Close();
if (dt != null && dt.Columns.Count > 0)
return dt;
else
return null;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
else
{
Console.WriteLine("Network is disconnect");
return null;
}
return null;
}
or :
public void ExecuteNonQuery(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

Categories

Resources