reading one record from access in C# - c#

My requirement is to read Date column from access file and use one value to append it to a file name, so as to create file with date timestamp using the db value.
I am trying following approach but it gives me exception "No data exists for the row/column":
here's the code
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbConnection conn1 = new OleDbConnection(connectionString);
string dt = "SELECT top 1 Date FROM Events";
OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
conn1.Open();
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = rdr.GetInt32(0).ToString();
rdr.Close();
conn1.Close();
string path = text_dir + "\\" + time_stmp + "_" + "BWC_Ejournal.txt";

You'll need to call the Read() method on the OleDbDataReader object before accessing its data.
E.g.
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = "";
if(rdr.Read())
{
time_stmp = rdr.GetInt32(0).ToString();
}
else
{
//handle no data situation here
}
This will also allow to handle a situation where no data is returned more gracefully too.

DATE is a reserved word in ACE/Jet SQL. Try this instead:
string dt = "SELECT TOP 1 [Date] FROM Events";
Edit
On taking a closer look at your code I notice that you create the OleDbCommand object before the connection is opened. I've seen that cause problems as well. FWIW, the following code works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace oleDbTest
{
class Program
{
static void Main(string[] args)
{
using (var con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\main.accdb;"))
{
con.Open();
using (var cmd = new OleDbCommand(
"SELECT TOP 1 [Date] FROM [Events]", con))
{
string time_stmp = Convert.ToDateTime(cmd.ExecuteScalar()).ToString("yyyyMMdd");
Console.WriteLine(time_stmp.ToString());
}
con.Close();
}
Console.WriteLine("Done.");
System.Threading.Thread.Sleep(2000);
}
}
}

Related

How To Create models Connect ODBC mySQL with Visual Studio

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Odbc;
using System.Data.SqlClient;
namespace BroNetNew.Models
{
public class DataConn
{
string MyConString = "Driver={MySQL ODBC 5.3 Unicode Driver};" +
"SERVER=localhost;" +
"DATABASE=Bee;" +
"UID=root;" +
"PASSWORD=123;" +
"OPTION=4";
OdbcConnection MyConnection = new OdbcConnection(myConString);
MyConnection.Open();
string sql = "SELECT * from member";
OdbcConnection conn = null;
OdbcCommand comm = null;
OdbcDataReader dr = null;
conn = new OdbcConnection(MyConString);
conn.Open();
comm = new OdbcCommand(sql, conn);
dr = comm.ExecuteReader();
}
}
I don't know how to make it work and how to get data from table member(MY DB name:Bee in MyConString)
Please Help ... I First time use asp.net MVC.
Thank You...
public class DataConn
{
string MyConString = "Driver={MySQL ODBC 5.3 Unicode Driver};" +
"SERVER=localhost;" +
"DATABASE=Bee;" +
"UID=root;" +
"PASSWORD=123;" +
"OPTION=4"; // ODBC connection
string Query = "SELECT * from member"; // Write Query
using (OdbcConnection c = new OdbcConnection(myConString)) //New Connection
{
OdbcCommand cmd = new OdbcCommand(Query, c);
c.Open(); // Connection Open
OdbcDataReader dr = cmd.ExecuteReader();
// dr will get all data u want
// Query better use "SELECT column[0], column[1] FROM `member`";
// dr.GetString(0); -> for column[0]
// dr.GetString(1); -> for column[1]
// do something...
}
}

Database connection doesn't work C#

I'm working on a program in C#. I created a database with MySQL on phpMyAdmin and I want to connect this database with my program.
After the connection I have to insert, update, delete and view all the data, but I have a problem: the connection doesn't work.
I post here my code for the connection:
public static string StringaConnessione = "Data Source=localhost;Database=agility;userid=root;password='';";
public static MySqlConnection Connessione = new MySqlConnection(StringaConnessione);
When I write the code for the insert button I have another problem (is certainly for the database)
Connessione.Open();
SQLDataAdapter SDA=new SqlDataAdapter("INSERT INTO GARA(nome_gara,giudice,località,data,tpsopm,tpmopm,tpstot,tpmtot)VALUES('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"','"+textBox8.Text+"')",Connessione);
SDA.SelectCommand.ExecuteNonQuery();
Connessione.Close();
MessageBox.Show("Dati salvati correttamente!");
May you help me, please? Thank you!
You can't use a SqlDataAdapter to talk to MySQL as that class is designed for use with Sql Server.
Use the MySqlDataAdapter instead.
You have so many problems with your code:
1) You are using static connection, there is Connection pool and it is your friend.
2) You are not using your connection in using block or in try/catch/finally/block
to ensure closing of connection on exception.
3) Blocker problem: You are using SqlDataAdapter instead of MySqlDataAdapter
4) Blocker problem You should define your Insert query in InsertCommand of the DataAdapter, it will not work with SelectCommand. Even better just use MySqlCommand and ExecuteNonQuery on it.
5) You are not protected from Sql Injection(Use MySqlCommand.Parameters)
6) Bad formatting of your variables, textboxes and db fields.
How your code will look optimally:
public static string connetionString= "Data Source=localhost;Database=agility;userid=root;password='';";
public void SomeMethod()
{
using(MySqlConnection conn = new MySqlConnection(connetionString));
{
conn.Open();
string query = #"INSERT INTO GARA
(nome_gara, giudice, località, data, tpsopm, tpmopm, tpstot, tpmtot)
VALUES
(#Param1, #Param2, #Param3, #Param4, #Param5, #Param6, #Param7, #Param8)";
MySqlCommand cmd = new MySqlCommand(#"query", conn);
cmd.Parameters.AddWithValue("#Param1", textBox1.Text);
cmd.Parameters.AddWithValue("#Param2", textBox2.Text);
cmd.Parameters.AddWithValue("#Param3", textBox3.Text);
cmd.Parameters.AddWithValue("#Param4", textBox4.Text);
cmd.Parameters.AddWithValue("#Param5", textBox5.Text);
cmd.Parameters.AddWithValue("#Param6", textBox6.Text);
cmd.Parameters.AddWithValue("#Param7", textBox7.Text);
cmd.Parameters.AddWithValue("#Param8", textBox8.Text);
cmd.ExecuteNonQuery();
}
}
i think you should discard all your code.
and find a valid one to start
for example this
http://roboardgod.blogspot.hk/2013/08/cmysql.html
you may need to add the reference MySql.Data.MySqlClient manually. check this post to add the reference
How do I add a reference to the MySQL connector for .NET?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace MySQLtest
{
class Program
{
static void Main(string[] args)
{ string dbHost = "";//db address, for example localhost
string dbUser = "";//dbusername
string dbPass = "";//dbpassword
string dbName = "";//db name
string connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlCommand command = conn.CreateCommand();
conn.Open();
String cmdText = "SELECT * FROM member WHERE level < 50";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
MySqlDataReader reader = cmd.ExecuteReader(); //execure the reader
while (reader.Read())
{
for (int i = 0; i < 4; i++)
{
String s = reader.GetString(i);
Console.Write(s + "\t");
}
Console.Write("\n");
}
Console.ReadLine();
conn.Close();
}
}
}

Connection to database

I am trying to create a class that I can use within my application to easily connect to my database and run queries as needed. I found this post but it is not quite working like I expect.
Here is my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
//a class that returns a connection to the database
namespace epaCUBE_Utility_Tool
{
public class epaCUBE_DB
{
public static SqlConnection GetConnection()
{
string str = "user id=MyUserName;" +
"password=MyPassword;server=myServer;" +
"database=myDatabase; " +
"connection timeout=30";
SqlConnection con = new SqlConnection(str);
con.Open();
return con;
}
}
}
and here is how I am trying to use it:
private void button1_Click(object sender, EventArgs e)
{
var connection = epaCUBE_DB.GetConnection();
connection.Open();
SqlDataReader rdr = null;
string CommandText = "SELECT Field1, Field2 FROM TableName";
SqlCommand cmd = new SqlCommand(CommandText, connection);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
this.comboBox1.Items.Add(rdr["Field1"].ToString() +
": " + rdr["Field2"].ToString());
}
connection.Close();
}
when I press the button I get an error
InvalidOperationException: The connection was not closed. The connection's current state is open.
What am I doing wrong?
Thanks,
Leslie
GetConnection calls Open for you, but you're calling it again manually after you called GetConnection. Call it inside GetConnection or outside, but not both places.
Problem is in GetConnection() you already open the connection. All these problems came with your static method.
This is not good way to do this, better to create a new instance of SqlConnection when you need and dispose after use. The underlying connection pooling will be able to manage the physical connections.
separate your UI with Data access, Here you read the data from database and same time adding items to controls. You need to re-factor the code.
You can have method like below to retrieve data
public List<string> GetFields()
{
List<string> fields = new List<string>();
string CommandText = "SELECT Field1, Field2 FROM TableName";
using (var connection = new SqlConnection(epaCUBE_DB.GetConnectionString()))
{
connection.Open();
using (var cmd = new SqlCommand(CommandText, connection))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
fields.Add(reader["Field1"].ToString() + ": " + reader["Field2"].ToString());
}
}
}
return fields;
}
You're trying to open a connection which is already open, this results in exception.
before opening the connection check the connection status and then open the connection
cmd.Connection.Open();
add the following check/cleanup code:
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
I program quite defensively; I expect faults to occur and try to handle that gracefully.
As such..
// Define this once in a class and re-use for every connection..
string myConnString = "user id=MyUserName;" +
"password=MyPassword;server=myServer;" +
"database=myDatabase; " +
"connection timeout=30";
using (SqlConnection mySqlConnection = new SqlConnection(myConnString))
{
using (SqlCommand mySQLCommand = new SqlCommand("SELECT Field1, Field2 FROM TableName", mySqlConnection) { CommandType = CommandType.Text})
{
try
{
mySqlConnection.Open();
using (SqlDataReader rdr = mySQLCommand.ExecuteReader())
{
this.comboBox1.Items.Add(rdr["Field1"].ToString() + ": " + rdr["Field2"].ToString());
}
}
catch (Excecption e)
{
// Deal with it as you wish
}
mySqlConnection.Close();
}
}

Gathering data from Access database

I want to gather some data from some tables of an Access Database, I've found some solutions online, but I haven't found ways to fill a datatable, or dataset, and get each single field properly.
Is it easier for me to get whole tables then get just the info that i want, or should I make a lot of searches in the access DB getting just what i Want each time? Any code snippets for it?
info:
The Access Database is in an ACCDB
file, with no user or password
I'm currently using VB.NET, but it
doesn't matter if you answer in C#
--[EDIT]--
Sub question:
Connecting to ACCDB format MS-ACCESS database through OLEDB
From here, you use the OleDbDataReader:
using System;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
class MainClass
{
static void Main(string[] args)
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
string sql = "SELECT * FROM Orders";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.Write(reader.GetString(0).ToString() + " ," );
Console.Write(reader.GetString(1).ToString() + " ," );
Console.WriteLine("");
}
reader.Close();
conn.Close();
}
}
If you can fill a DataSet, you have all data (fields) in memory.
In your Project, use the Data menu to add a DataSource.
Follow the Wizard. It will create a Typed DataSet for you.
Drag the new DataSource to a Form. That will show you the code to fill the DS.
I wrote this test program to retrieve data from a DAO database. This should work for you too.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace TestReadCfg
{
class Program
{
static void Main(string[] args)
{
string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "c:\\Avtron\\addapt\\Configuration\\testDao.db;Jet OLEDB:Database Password=RainbowTrout;";
string queryString = "SELECT * from Sections order by Address";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// Create the Command and Parameter objects.
OleDbCommand command = new OleDbCommand(queryString, connection);
try
{
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
int iRecNbr = 1;
while (reader.Read())
{
String sRecord = string.Empty;
sRecord = string.Format("Record {0}: ", iRecNbr);
for (int i = 0; i < reader.FieldCount; i++)
{
sRecord += string.Format("{0} ", reader[i].ToString());
}
Console.WriteLine(sRecord);
iRecNbr++;
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}

How do I connect to a database and loop over a recordset in C#?

What's the simplest way to connect and query a database for a set of records in C#?
#Goyuix -- that's excellent for something written from memory.
tested it here -- found the connection wasn't opened. Otherwise very nice.
using System.Data.OleDb;
...
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";
using (OleDbCommand cmd = new OleDbCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Select * from yourTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Console.WriteLine(dr["columnName"]);
}
}
}
}
Very roughly and from memory since I don't have code on this laptop:
using (OleDBConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Whatever connection string";
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "Select * from CoolTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// do something like Console.WriteLine(dr["column name"] as String);
}
}
}
}
That's definitely a good way to do it. But you if you happen to be using a database that supports LINQ to SQL, it can be a lot more fun. It can look something like this:
MyDB db = new MyDB("Data Source=...");
var q = from db.MyTable
select c;
foreach (var c in q)
Console.WriteLine(c.MyField.ToString());
This is an alternative way (DataReader is faster than this one):
string s = "";
SqlConnection conn = new SqlConnection("Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 name, dbid FROM sysdatabases", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
s += dt.Rows[i]["name"].ToString() + " -- " + dt.Rows[i]["dbid"].ToString() + "\n";
}
MessageBox.Show(s);
If you are intending on reading a large number of columns or records it's also worth caching the ordinals and accessing the strongly-typed methods, e.g.
using (DbDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
int idxColumnName = dr.GetOrdinal("columnName");
int idxSomethingElse = dr.GetOrdinal("somethingElse");
do {
Console.WriteLine(dr.GetString(idxColumnName));
Console.WriteLine(dr.GetInt32(idxSomethingElse));
} while (dr.Read());
}
}
If you are querying a SQL Server database (Version 7 and up) you should replace the OleDb classes with corresponding classes in the System.Data.SqlClient namespace (SqlConnection, SqlCommand and SqlDataReader) as those classes have been optimized to work with SQL Server.
Another thing to note is that you should 'never' select all as this might lead to unexpected results later on if you add or remove columns to this table.
I guess, you can try entity framework.
using (SchoolDBEntities ctx = new SchoolDBEntities())
{
IList<Course> courseList = ctx.GetCoursesByStudentId(1).ToList<Course>();
//do something with courselist here
}
Charge the libraries
using MySql.Data.MySqlClient;
This is the connection:
public static MySqlConnection obtenerconexion()
{
string server = "Server";
string database = "Name_Database";
string Uid = "User";
string pwd = "Password";
MySqlConnection conect = new MySqlConnection("server = " + server + ";" + "database =" + database + ";" + "Uid =" + Uid + ";" + "pwd=" + pwd + ";");
try
{
conect.Open();
return conect;
}
catch (Exception)
{
MessageBox.Show("Error. Ask the administrator", "An error has occurred while trying to connect to the system", MessageBoxButtons.OK, MessageBoxIcon.Error);
return conect;
}
}

Categories