What is the namespace while creating a MS Access database using C# - c#

I am exporting a gridview to MS Access but I am facing some problems.
What namespace I should be using while creating a MS access database in C#?

For playing with Microsoft office realated document like MS-Access or MS-Excel you need to add
using System.Data.OleDb

write some code
OleDbConnection conn = new OleDbConnection();
then right click on the class name (e.g. OleDbConnection) and select resolve or you can use shortcut ctrl + .
In this specific case you need to add
using System.Data.OleDb

You need to add reference to this namespace in your project System.Data.OleDb
and then use it on you file like this
using System.Data.OleDb

The System.Data.OleDb namespace needs to be added in your c# file. You can refer the below detailed sample which help you to learn more about MS Access data storage and retrieval through C#.
Link to Refer

I am using 2 namespace
using ADOX;
Using ADODB;

yes i am using namespace
using System.Data.OLEDB; with 2 namespace
using ADOX;
using ADODB; with this code
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;

Related

C# variable in a MySql query isn't recognized

I have an int variable in my C# code and I'm trying to use it in a MySql query.
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 MySql.Data;
using MySql.Data.MySqlClient;
namespace projeV1
{
public partial class ProjeDetay : Form
{
public ProjeDetay()
{
InitializeComponent();
}
private void ProjeDetay_Load(object sender, EventArgs e)
{
int satir_projem = Projeler.satir_proje;
string connectionString = "Server = localhost; Port = ...; Database = ...; Uid = root; Pwd = ...; Allow User Variables=True";
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand command;
databaseConnection.Open();
command = databaseConnection.CreateCommand();
string myQuery = "select projeAdi from projeler where projeID = #satir_projem";
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(myQuery, databaseConnection);
command.Parameters.Add("#satir_projem", MySqlDbType.Int32).Value = satir_projem;
DataSet DS = new DataSet();
dataAdapter.Fill(DS);
dataGridView_ProjeDetay.DataSource = DS.Tables[0];
MessageBox.Show(Projeler.satir_proje.ToString());
MessageBox.Show(satir_projem.ToString());
}
}
}
(Sorry if it looks like a mess in regard to coding but I'm new at this ^^)
MessageBox windows show the variables' values correctly, so there's no problem with the variable. And when I replace#satir_projem from the query string with a number like "2" (see the example below), for example, the result is correct, but when I use #satir_projem in the query, it doesn't work. I can't see what I'm doing wrong.
Example query string:
"select projeAdi from projeler where projeID = 2"
P.S 1: Originally I'm trying to get the index of the selected row (which is the variable called Projeler.satir_proje) in a DataGridView used in a form called "Projeler" and in another form (which is called ProjeDetay), assigning that index value into another variable called "satir_projem" and use this value to get the related data from my database and put that data in another DataGridView located in my second form (which is called dataGridView_ProjeDetay).
P.S 2: I've made a lot of research about this problem and tried many of the solutions I encountered along the way; however, none of them worked for me. So, here I am :)
Thanks in advance.
You are setting parameter for command that is not used.
Instead you should use DataAdapter.SelectCommand
dataAdapter.SelectCommand.Parameters.Add(...)
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand command;
string myQuery = "select projeAdi from projeler where projeID = #satir_projem";
databaseConnection.Open();
command = new MySqlCommand(myQuery, databaseConnection);
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command);
Just want to elaborate, why #Onur_Saatcioglu's code is throwing error.
you are adding #satir_projem to command but the parameter thus added to command is not being passed to dataadapter which serves as a bridge between a DataSet and SQL Server for retrieving and saving data.
Hence you can
1) As Lester told, create command like
command = new MySqlCommand(myQuery, databaseConnection);
and pass the command to DataAdapter
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command);
2) As #Pablo_notPicasso said, if you are using
dataAdapter.SelectCommand.Parameters.AddWithValue("#satir_projem", satir_projem);
then "command" does not make sense, you can just delete it.

Executing Stored Procedure using C#

I have a procedure named as Get_Added_Request_ID and using this procedure I need to get returned the Request_ID value (VARCHAR2). I have referrd plenty of docs released by Oracle and Microsoft but still I could not find a good solution may be because I am a new learner for Oracle and ASp.NET. Please someone help me in this issue. Thanks in advance
-- Parameter Type Mode Default?
-- ATTR_ VARCHAR2 IN
-- REQUEST_ID VARCHAR2 OUT
Please view this link for the documentation on how to connect to oracle by using oracle data provider
You should use oracle data provider from this link for connecting oracle.
the example code for your scenario will be
Using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OracleClient;
using System.Data;
namespace CallingOracleStoredProc
{
class Program
{
static void Main(string[] args)
{
using (OracleConnection objConn = new OracleConnection("Data Source=*your datasource*; User ID=*Your UserID*; Password=*Your Password*"))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "Get_Added_Request_ID";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("ATTR_", OracleType.NVarChar).Value = "test";
objCmd.Parameters.Add("REQUEST_ID", OracleType.NVarChar).Direction = ParameterDirection.Output;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
System.Console.WriteLine("The Request ID is {0}", objCmd.Parameters["REQUEST_ID"].Value);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception: {0}",ex.ToString());
}
objConn.Close();
}
}
}
}
use execute scalar which return 1 row - 1 column value & store it in appropriate variable
For e.g :- SqlHelper.ExecuteScalar(_connectionString, CommandType.StoredProcedure, "Get_Added_Request_ID", null);
note :- ExecuteScalar is came from nuget Microsoft.Application Block

.NET Framework compatibility issue with Oracle Data Access

I'm working on a C# project in Visual Studio 2012 on Windows 10 and Oracle 11g.
In order to connect my c# project I had to install Oracle Data Access Components_ODTwithODAC121024 and everything worked fine.
I updated the target .NET framework of my project to 3.5, and now I get this error:
Could not load file or assembly 'Oracle.DataAccess, Version=2.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. An attempt was made to load a program with an incorrect format.
After really long search and test I think that caused by incompatibility issue.
I tried to enable .NET Framework 3.5 through Programs and Features -> Turn Windows features on or off.
I tried to read reference and importing the Oracle.DataAccess.dll from
C:\app\Samer\product\11.2.0\dbhome_1\ODP.NET\bin\2.x
and I also used the Oracle.DataAccess.dll that comes with Oracle Data Access Components
My project works fine when I disable the method that deals with oracle commands.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace backup_Check_v01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Read_const_File();
}
//Method for Reading Constants File
public void Read_const_File()
{
string File_Path;
File_Path = #"s:\test\result";
Get_File_info(File_Path);
}
//Method for reading file information ex(File Name,Size,and creation date..etc)
public void Get_File_info(string para1)
{
FileInfo info = new FileInfo(para1);
richTextBox1.AppendText(Environment.NewLine + "File Name: " + Path.GetFileNameWithoutExtension(info.Name));
richTextBox1.AppendText(Environment.NewLine + "File Size (Bytes): " + info.Length.ToString());
richTextBox1.AppendText(Environment.NewLine + "Creation Time: " + info.CreationTime.ToString());
richTextBox1.AppendText(Environment.NewLine + "Last Access: " + info.LastAccessTime.ToString());
richTextBox1.AppendText(Environment.NewLine + " **************************** ");
search_for_string(para1);
}
public void search_for_string(string para2)
{
string keywords = "sb_0501_Thu.dmp";
string oradb = "Data Source=sb_1901;User Id=sb_1901;Password=sb00;";
StreamReader sr = new StreamReader(para2);
richTextBox1.AppendText(Environment.NewLine + sr.ReadToEnd());
if (!richTextBox1.Text.Contains(keywords))
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',0,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
else
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',1,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
}
}
}
You refer to ODP.NET version 2.121.2.0. but it seems you have installed Oracle Client 11.2. The versions have to match with each other (at least the major version number)
Open your *.csproj file and set reference of Oracle.DataAccess like this:
<Reference Include="Oracle.DataAccess">
<SpecificVersion>False</SpecificVersion>
</Reference>
Attributes like Version=... or processorArchitecture=... are not required. Your application will load the correct Oracle.DataAccess.dll depending on selected architecture and target .NET framework

Unrecognized database format

I would like to ask, why I get this exception when I try to connect excel 2000/3 and also 2010?
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
namespace md1_connect
{
class Program
{
static void Main (string[] args)
{
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Book1.xls\"";
OleDbConnection MyConn = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM[Sheet2$]", MyConn);
MyConn.Open();
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Console.WriteLine(dataReader.GetDouble(0));
}
MyConn.Close();
}
}
}
You need to tell the provider you're using Excel 97-2003 (xls as opposed to xlsx) by appending:
Extended Properties="Excel 8.0"
E.g.
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Book1.xls\";Extended Properties=\"Excel 8.0\"";
I dont know what the exception is but I may know what you are talking about. You are probably compiling as x64 bit, please force it to run as 32 bit (x86). I believe that setting can be set in your Project Properties under Build Options

Where/how do I write T-SQL in my C# code and get the result (Visual Studio 2008)

I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement

Categories

Resources