473,581 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Run a SQL Query

How can I run this query against a table in my Access database? I don't know
hwo to use it in C#. In VB I would use .Recordset = "some sql statement". How
do I do this in C#?

//I get a vlaue form a cell and apply it to the SQL statement
commandCol = scriptDataGridV iew[4, rowNum].FormattedValue .ToString();
string sCommand = "SELECT CommandString FROM Commands WHERE CommandName = "
+ commandCol;
//This reutne a valie SQL statement which will return the Command String in
the database table but how?

Thanks
Feb 14 '07 #1
2 17637
Hi,

"Chris" <Ch***@discussi ons.microsoft.c omwrote in message
news:60******** *************** ***********@mic rosoft.com...
How can I run this query against a table in my Access database? I don't
know
hwo to use it in C#. In VB I would use .Recordset = "some sql statement".
How
do I do this in C#?

//I get a vlaue form a cell and apply it to the SQL statement
commandCol = scriptDataGridV iew[4, rowNum].FormattedValue .ToString();
string sCommand = "SELECT CommandString FROM Commands WHERE CommandName =
"
+ commandCol;
//This reutne a valie SQL statement which will return the Command String
in
the database table but how?
http://www.csharp-station.com/Tutori.../Lesson01.aspx

--
Ignacio Machin
machin AT laceupsolutions com
Feb 14 '07 #2
Below class with populate dataset with "whole" database, includes
GetRow(tablenam e,query); hope this helps.

using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Data.Sql Client;
using System.Data;
using System.Collecti ons;

namespace SQL
{
public static class Data
{

#region Population
public static void NewSQLConnectio n()
{
string datasource = ApplicationSett ings.MeetySetti ngs.DNS + "\\"
+ ApplicationSett ings.MeetySetti ngs.Instance;
string connectionStrin g = "user id=" +
ApplicationSett ings.MeetySetti ngs.Username +
"; pwd=" + ApplicationSett ings.MeetySetti ngs.Password +
"; Initial Catalog=" +
ApplicationSett ings.MeetySetti ngs.TableName +
"; Data Source=" + datasource +
";Packet Size=4096" +
";Connectio n Timeout=5;";

ApplicationSett ings.MeetySetti ngs.SQLConnecti on = new
SqlConnection(c onnectionString );
ApplicationSett ings.MeetySetti ngs.SQLConnecti on.StatisticsEn abled
= true;
}

public static string PopulateDataSet ()
{
try
{
ApplicationSett ings.MeetySetti ngs.SQLConnecti on.Open();
ApplicationSett ings.MeetySetti ngs.HashTable = new
System.Collecti ons.Hashtable() ;

ApplicationSett ings.MeetySetti ngs.DataSet = new
DataSet("System ");
SqlDataAdapter adapter = null;
string query = "SELECT TABLE_NAME as 'Table' from
INFORMATION_SCH EMA.tables WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME !=
'dtproperties' ORDER BY TABLE_NAME ASC";

adapter = new SqlDataAdapter( );
adapter.Missing SchemaAction =
System.Data.Mis singSchemaActio n.AddWithKey;
adapter.SelectC ommand = new SqlCommand(quer y,
ApplicationSett ings.MeetySetti ngs.SQLConnecti on);

adapter.Fill(Ap plicationSettin gs.MeetySetting s.DataSet,
"Tables");
query = "SELECT KCU1.CONSTRAINT _NAME AS 'FK',
KCU1.TABLE_NAME AS 'FK_Table', KCU1.COLUMN_NAM E AS 'FK_Column',
KCU2.CONSTRAINT _NAME AS 'PK', KCU2.TABLE_NAME AS 'PK_Table',
KCU2.COLUMN_NAM E AS 'PK_Column' FROM
INFORMATION_SCH EMA.REFERENTIAL _CONSTRAINTS RC JOIN
INFORMATION_SCH EMA.KEY_COLUMN_ USAGE KCU1 ON KCU1.CONSTRAINT _CATALOG =
RC.CONSTRAINT_C ATALOG AND KCU1.CONSTRAINT _SCHEMA = RC.CONSTRAINT_S CHEMA AND
KCU1.CONSTRAINT _NAME = RC.CONSTRAINT_N AME JOIN
INFORMATION_SCH EMA.KEY_COLUMN_ USAGE KCU2 ON KCU2.CONSTRAINT _CATALOG =
RC.UNIQUE_CONST RAINT_CATALOG AND KCU2.CONSTRAINT _SCHEMA =
RC.UNIQUE_CONST RAINT_SCHEMA AND KCU2.CONSTRAINT _NAME =
RC.UNIQUE_CONST RAINT_NAME AND KCU2.ORDINAL_PO SITION = KCU1.ORDINAL_PO SITION
ORDER BY KCU1.TABLE_NAME ";

adapter = new SqlDataAdapter( );
adapter.Missing SchemaAction =
System.Data.Mis singSchemaActio n.AddWithKey;
adapter.SelectC ommand = new SqlCommand(quer y,
ApplicationSett ings.MeetySetti ngs.SQLConnecti on);

adapter.Fill(Ap plicationSettin gs.MeetySetting s.DataSet,
"Relations" );
query = "SELECT TC.TABLE_NAME as 'PK_Table', CSU.COLUMN_NAME
as 'PK_Column', CSU.CONSTRAINT_ NAME as 'PK_Name' FROM
INFORMATION_SCH EMA.CONSTRAINT_ COLUMN_USAGE CSU JOIN
INFORMATION_SCH EMA.TABLE_CONST RAINTS TC ON CSU.CONSTRAINT_ NAME =
TC.CONSTRAINT_N AME WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'";

adapter = new SqlDataAdapter( );
adapter.Missing SchemaAction =
System.Data.Mis singSchemaActio n.AddWithKey;
adapter.SelectC ommand = new SqlCommand(quer y,
ApplicationSett ings.MeetySetti ngs.SQLConnecti on);

adapter.Fill(Ap plicationSettin gs.MeetySetting s.DataSet,
"Primary");

string name = string.Empty;

foreach (DataRow dr in
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les["Tables"].Rows)
{
name = dr["Table"].ToString();
query = "SELECT * FROM " + name;
adapter = new SqlDataAdapter( );
adapter.Missing SchemaAction =
System.Data.Mis singSchemaActio n.Add;
adapter.SelectC ommand = new SqlCommand(quer y,
ApplicationSett ings.MeetySetti ngs.SQLConnecti on);
SqlCommandBuild er commandBuilder = new
SqlCommandBuild er(adapter);
ApplicationSett ings.MeetySetti ngs.HashTable.A dd(name,
adapter);
adapter.Fill(Ap plicationSettin gs.MeetySetting s.DataSet,
name);

DataRow[] ucRows =
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les["Primary"].Select("PK_Tab le
= '" + name + "'");
if (ucRows != null && ucRows.Length 0)
{
string pkName = (string)ucRows[0]["PK_Name"];
DataColumn[] cols = new DataColumn[ucRows.Length];
for (int i = 0; i < ucRows.Length; i++)
{
cols[i] =
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les[name].Columns[ucRows[i]["PK_Column"].ToString()];
}
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les[name].Constraints.Ad d(pkName,
cols, true);

}
}

foreach (DataRow dr in
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les["Relations"].Rows)
{
name = dr["FK"].ToString();
if (name.IndexOf(" Archive") >= 0 || name == "Images")
continue;
string pkTable = dr["PK_Table"].ToString();
string pkCol = dr["PK_Column"].ToString();
string fkTable = dr["FK_Table"].ToString();
string fkCol = dr["FK_Column"].ToString();
ApplicationSett ings.MeetySetti ngs.DataSet.Rel ations.Add(name ,
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les[pkTable].Columns[pkCol],
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les[fkTable].Columns[fkCol]);

}

ApplicationSett ings.MeetySetti ngs.DataSet.Tab les.Remove("Tab les");
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les.Remove("Pri mary");
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les.Remove("Rel ations");
}
catch (Exception ex)
{
return "Error connecting to database - " + ex.Message;
}
finally
{
ApplicationSett ings.MeetySetti ngs.SQLConnecti on.Close();
}

return null;
}
#endregion

#region Manipulation
public static int SQLTableUpdate( string tableName)
{
int ret = -1;
SqlDataAdapter sqlAdapter = null;

sqlAdapter =
(SqlDataAdapter )ApplicationSet tings.MeetySett ings.HashTable[tableName];
try { ret =
sqlAdapter.Upda te(ApplicationS ettings.MeetySe ttings.DataSet, tableName); }
catch
{

}

return ret;
}

public static void AddNewRow(strin g table, DataRow row)
{
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les[table].Rows.Add(row);
SQLTableUpdate( table);
}

public static DataView GetDV(string table, string filter)
{
DataView dv = null;

dv = new
DataView(Applic ationSettings.M eetySettings.Da taSet.Tables[table]);
dv.RowFilter = filter;

return dv;
}
public static System.Data.Dat aRow GetNewRow(strin g table)
{
return
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les[table].NewRow();
}

public static DataRow GetSingleRow(st ring table, string filter)
{
DataRow[] rows = null;

rows =
ApplicationSett ings.MeetySetti ngs.DataSet.Tab les[table].Select(filter) ;
if (rows.Length 0)
return rows[0];
else
return null;
}
public static string GetIncrementedI D(DataView dv, string idColumn)
{
return GetIncrementedI D(dv.Table, idColumn);
}
public static string GetIncrementedI D(string dt, string idColumn)
{
return
GetIncrementedI D(ApplicationSe ttings.MeetySet tings.DataSet.T ables[dt],
idColumn);
}
public static string GetIncrementedI D(System.Data.D ataTable dt,
string idColumn)
{
if (dt.Rows.Count == 0)
{
return GetInitialID(dt .TableName);
}
else
{
string max = (string)dt.Comp ute("MAX(" + idColumn + ")",
"");
string[] split = max.Split(new char[] { '_' });
int recordCounter = Convert.ToInt32 (split[1]);
recordCounter++ ;

string newID = NumberToString( recordCounter,
split[1].Length);
return split[0] + "_" + newID;
}

}
private static string NumberToString( int number, int places)
{
string num = number.ToString ();
string ret = string.Empty;
if (num.Length >= places)
ret = num;
else
{
ret = new string('0', places - num.Length);
ret += num;
}
return ret;
}
private static string NumberToString( int number, string template)
{
string num = number.ToString ();
string ret = string.Empty;
if (num.Length >= template.Length )
ret = num;
else
{
ret = new string('0', template.Length - num.Length);
ret += num;
}
return ret;
}
private static string GetInitialID(st ring tableName)
{
switch (tableName)
{
case "Mail_Queue ":
return "JJM_0001";
case "Department s":
return "DEP_0001";
}
return string.Empty;
}
#endregion
}
}

Regards j1mb0jay (UWA)
Feb 14 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3423
by: jaysonsch | last post by:
Hello! I am having some problems with a database query that I am trying to do. I am trying to develop a way to search a database for an entry and then edit the existing values. Upon submit, the new values are updated in all corresponding tables (the function of the pages in question). However, on the page that does the DB update, I also...
29
2477
by: shank | last post by:
1) I'm getting this error: Syntax error (missing operator) in query expression on the below statement. Can I get some advice. 2) I searched ASPFAQ and came up blank. Where can find the "rules" for when and how to use single quotes and double quotes in ASP? thanks! ---------------------- SQL = SQL & "WHERE '" &...
9
3120
by: netpurpose | last post by:
I need to extract data from this table to find the lowest prices of each product as of today. The product will be listed/grouped by the name only, discarding the product code - I use SUBSTRING(ProductName, 1, CHARINDEX('(', ProductName)-2). I can get this result, but I had to use several views (totally inefficient). I think this can be...
3
5378
by: Harvey | last post by:
Hi, I try to write an asp query form that lets client search any text-string and display all pages in my web server that contain the text. I have IIS 6.0 on a server 2003. The MSDN site says there is a sample file called Ixtrasp.asp, but I could not find it in my system although I installed indexing service. I followed the steps in MSDN...
4
2137
by: Diamondback | last post by:
I have two tables, WIDGETS and VERSIONS. The WIDGETS table has descriptive information about the widgets while the VERSIONS table contains IDs relating to different iterations of those widgets over the years. The idea is that from any widget in the database you can look forward and backward to see different versions of the widget through...
14
3871
by: Dave Thomas | last post by:
If I have a table set up like this: Name | VARCHAR Email | VARCHAR Age | TINYINT | NULL (Default: NULL) And I want the user to enter his or her name, email, and age - but AGE is optional. My insert would look something like:
0
3493
by: starace | last post by:
I have designed a form that has 5 different list boxes where the selections within each are used as criteria in building a dynamic query. Some boxes are set for multiple selections but these list boxes do not necessarily need to have a selection made to be used in the dynamic query. In essence the form can have selections made in all or...
6
4832
by: jjturon | last post by:
Can anyone help me?? I am trying to pass a Select Query variable to a table using Dlookup and return the value to same select query but to another field. Ex. SalesManID SalesManName AT Alan Time
4
3120
by: Stan | last post by:
I am using MS Office Access 2003 (11.5614). My basic question is can I run a query of a query datasheet. I want to use more that one criteria and can not get that query to work. I thought I might be able to accomplish the results in two steps by using two queries. If this is possible how can I do it? Thank you, Stan Hanna
6
4386
by: jsacrey | last post by:
Hey everybody, got a secnario for ya that I need a bit of help with. Access 97 using linked tables from an SQL Server 2000 machine. I've created a simple query using two tables joined by one field between them. The join field in both tables are indexed and I'm selecting 1 field from each table to lookup. The Access query is taking more...
0
7808
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8312
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7914
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5683
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5366
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3835
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1410
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1145
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.