Sql query not returning all results - c#

I'm using an OLEDB Command to run a basic query on a .mdb file like so:
List<TPRItem> itemList = new List<TPRItem>();
string connStr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dirPath;
string sql = "SELECT UPC, ItemDesc, TPRAllow, NetCost, UnitCost, Pack, TPREndDate FROM OrderGuide WHERE TPRAllow > 0";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
OleDbCommand cmd = new OleDbCommand(sql, conn);
try
{
conn.Open();
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
TPRItem thisTPRItem = new TPRItem();
thisTPRItem.UPC = rdr["UPC"].ToString();
thisTPRItem.VendorDescription = rdr["ItemDesc"].ToString();
thisTPRItem.CaseAllowance = decimal.Parse(rdr["TPRAllow"].ToString());
thisTPRItem.CaseCost = decimal.Parse(rdr["NetCost"].ToString());
thisTPRItem.UnitCost = decimal.Parse(rdr["UnitCost"].ToString());
thisTPRItem.CsPack = int.Parse(rdr["Pack"].ToString());
thisTPRItem.EndDate = DateTime.Parse(rdr["TPREndDate"].ToString());
thisTPRItem.CaseAllowanceCost = thisTPRItem.CaseCost - thisTPRItem.CaseAllowance;
thisTPRItem.UnitAllowanceCost = thisTPRItem.CaseAllowanceCost / thisTPRItem.CsPack;
itemList.Add(thisTPRItem);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Only 2365 items are added to my list. However when I run this exact same query in Access I get 10867 results.
I am accessing a .mdb file that changes from month to month (the data changes not the format) and previously we have not had issues with missing items.

Change your provider to a higher version.

Related

Import data from one MS Access database into another MS Access database

I am trying to import data from one MS Access database into another MS Access database and have found the following works fine, problem I have got is does anybody know what I should be using if the from database is locked with a SYSTEM.MDW
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\Database1.mdb;User Id=admin;Password=;";
string commandText = "INSERT INTO [TableName] SELECT * FROM [MS Access;DATABASE=C:\\Data\Database2.mdb].[TableName]";
try
{
using (OleDbConnection oleConnection = new OleDbConnection(connectionString))
{
using (OleDbCommand oleCommand = new OleDbCommand(commandText, oleConnection))
{
oleCommand.CommandType = CommandType.Text;
oleCommand.Connection.Open();
oleCommand.ExecuteNonQuery();
}
}
}
catch (Exception)
{
throw;
}
I can open the From database using Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Database2.MDB;System Database=C:\Data\SYSTEM.MDW;User ID=Developer;Password=Password
If you can open the From database, open it and do the action from it:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Database2.MDB;System Database=C:\Data\SYSTEM.MDW;User ID=Developer;Password=Password";
string commandText = "INSERT INTO [TableName] In 'C:\\Data\Database1.mdb' SELECT * FROM [TableName]";
try
{
using (OleDbConnection oleConnection = new OleDbConnection(connectionString))
{
using (OleDbCommand oleCommand = new OleDbCommand(commandText, oleConnection))
{
oleCommand.CommandType = CommandType.Text;
oleCommand.Connection.Open();
oleCommand.ExecuteNonQuery();
}
}
}
catch (Exception)
{
throw;
}

How to make 2 select statements in one query?

i got a database table that contains:
Name,X,Y,Z
here's the part i'm selecting some values from the database :
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "SELECT Name , X, Y, Z FROM gestures ";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
FromDB.Name = myReader[0].ToString();
MPoint asdd = new MPoint((double)myReader[1], (double)myReader[2], (double)myReader[3]);
FromDB.FDB.Add(asdd);
}
files.Add(FromDB);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
what i'm asking for is how to select distinct name instead of selecting the repeated names and selecting all the X,Y,Z points even the repeated ones
i hope i clarified my question
To select all records on a unique column from a MySQL database using C#:
using MySql.Data.MySqlClient;
...
var connectionString = "<insert connection string here>";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "select * from gestures group by name";
var command = new MySqlCommand(query, connection);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var name = reader.GetString(0);
var pointX = reader.GetInt32(1);
var pointY = reader.GetInt32(2);
var pointZ = reader.GetInt32(3);
Console.WriteLine($"{name}: {x},{y},{z}");
}
}
}
Edit: Link to MySQL C# documentation.

MYSql with C# in Visual Studio. How to return a boolean if a database exists

I'm working on a WPF MVVM Light application and I'd like to have a Boolean Method that uses a MYSql Query and C# to Progammatically determine if the Database exists. Any ideas would be greatly appreciated.
Maybe something with a query like :
SELECT IF(EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'Mark'), 'Yes','No')
Or:
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DBName'
I've got methods that will query the database but I'd like to have a checksum that determines if the db exists. If I use the code below it will error out so I'd like to determine first if the db exists and if it does query it.
static public Project.Project QueryProject(string projDatabaseName)
{
Project.Project proj = new Project.Project();
string connStr = "server=localhost;database=" + projDatabaseName + ";user=******;port=3306;password=********;";
string queryStr = "SELECT * FROM " + projDatabaseName + ".project";
MySqlConnection myConnection = new MySqlConnection(connStr);
MySqlCommand myCommand = new MySqlCommand(queryStr, myConnection);
myConnection.Open();
try
{
MySqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
proj.ProjectID = int.Parse(myReader["ProjectID"].ToString());
proj.ProjectName = myReader["ProjectName"].ToString();
proj.ProjectStartDate = Convert.ToDateTime(myReader["ProjectStartDate"]);
proj.ProjectEndDate = Convert.ToDateTime(myReader["ProjectEndDate"]);
proj.ProjectNotes = myReader["ProjectNotes"].ToString();
}
myReader.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
finally
{
myConnection.Close();
}
return proj;
}
use INFORMATION_SCHEMA as the database the use show databases.
public bool DatabaseExists(string dbname)
{
string connStr = "server=localhost;database=INFORMATION_SCHEMA;";
using (MySqlConnection myConnection = new MySqlConnection(connStr))
{
string sql = "show databases";
MySqlCommand myCommand = new MySqlCommand(sql, myConnection);
myConnection.Open();
MySqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
string db = myReader["Database"].ToString();
if (db == dbname)
return true;
}
}
return false;
}
Try this:
SHOW DATABASES LIKE 'databaseName';
It returns an empty set if it doesn't exist.

Equivalent C# of this PHP code

Trying to learn C# and I can't quite get a handle on querying and getting results. I'm trying to figure out both how to and the best way of doing the below in C# .NET. It's a MySql database.
//Interact with the DB. Find out if this hashed account #'s in there.
$dbh = $this->getPDO();
$procedure = "SELECT userPass FROM 499Users WHERE accName = :acc";
$call = $dbh->prepare($procedure);
$call->bindParam(':acc', $testAcc, PDO::PARAM_STR);
$call->execute();
//Fetch up to 1 result row
$row = $call->fetch(PDO::FETCH_ASSOC);
This is my latest try: Also I realize I should probably be using parameters, but I just want it to work first
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "*";
conn_string.UserID = "*";
conn_string.Password = "*";
conn_string.Database = "*";
conn_string.Port = 3306;
MySqlConnection connection = new MySqlConnection(conn_string.ToString());
try
{
Console.WriteLine("Trying to connect to: ..." + conn_string); Console.WriteLine("Connecting to MySQL...");
connection.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
string hashedAcc = this.HashPassword(acc);
//Verify hashed account
string query = "SELECT userPass FROM 49Users WHERE accName =" + hashedAcc;
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader myReader;
myReader = cmd.ExecuteReader();
try
{
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
}
finally
{
myReader.Close();
connection.Close();
}
The following WHERE clause:
WHERE accName =" + hashedAcc;
will cause an error if accName is not of type int, it needs quotes around it.
You should use parameterized query just like you did in PDO, it avoid errors like this and SQL injections as well.
var query = "SELECT userPass FROM 49Users WHERE accName = #hashedAcc";
var cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("#hashedAcc", hashedAcc);

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