Using an MS Access Lookup field in C# - c#

I am building an extension to an existing Access database and an accompanying front end programmed in C#. The original Access database was not designed very well and certainly not designed with future expansion in mind. For simplicity's sake, lets say the legacy DB has 2 tables: tblEmployee [empId(AutoNumber), empName(Text)] and tblProjects [prjId(AutoNumber), prjName(Text), prjEmps(Number/Lookup)]. Both tables have an AutoNumber primary key. The Projects table has a multi-value lookup field that allows users to assign multiple employees to a project. When I query the tblProjects table in Access SELECT prjId, prjName, prjEmps FROM tblProject;, the prjEmps field lists all the employees' names separated by commas. However, the problem is when I use the same query in C#, the prjEmps returns a string version of a number that is not the empId of the employee(s). I am not sure if it makes a difference, but I am using the System.Data.OleDb and System.Data namespaces in C#. Here is the gist my C# code:
string connStr = #"Provider = Microsoft.ACE.OLEDB.12.0; " +
#"Data Source=" + dbFilePath;
string query = "SELECT prjId, prjName, prjEmps FROM tblProject;";
OleDbConnection dbConn = new OleDbConnection(connStr);
OleDbCommand Cmd = new OleDbCommand(query, dbConn);
OleDbDataAdapter adp = new OleDbDataAdapter(query, dbConn);
DataTable dt = new DataTable();
adp.Fill(dt);
dbConn.Close();
foreach (DataRow row in dt.Rows)
{
int prjId = row.Field<int>("prjId");
string prjName = row.Field<string>("prjName");
string prjEmps = row.Field<string>("prjEmps");
MessageBox.Show("Project ID: " + prjId.ToString() + "\n" +
"Project Name: " + prjName + "\n" +
"Employees: " + prjEmps);
}
I would be happy if I could just get the concatenated list of names, but I would prefer an array of integer keys or the like. Any ideas on how to fix this?

Use ODBC provider, OLEDB does not supports multi-value lookup field and you get garbage values if you use it to read multi-value lookup field , using ODBC you will get ";" separated values which can then be split into individual values or replace with ",".

Related

change sql query using selected text in combobox

I'm writing a program using MySQL and WinForm. In my program there's an option to select a VAT Number from a combobox that is retrieve from a table in database. After selecting a VAT Number user have to enter 2 different values into 2 different textbox. After entering those values, the sql query will execute. And show the result in another textbox.
Application form
My sql queries are working fine.
using(MySqlConnection con = new MySqlConnection(cs))
{
con.Open();
//string command;
string command = #"SELECT * FROM `db_liq_blnd_calc_sys`.`tbl_vat_12_spirit_sa` WHERE DIP = '" + txt_Calc_BULK_DIP.Text + "' AND SLIDE = '" + txt_Calc_BULK_SLIDE.Text + "'";
MySqlDataAdapter da = new MySqlDataAdapter(command, con);
DataTable dtable = new DataTable();
DataSet ds = new DataSet();
da.Fill(ds);
DataRow[] returnrow = ds.Tables[0].Select("DIP = '" + txt_Calc_BULK_DIP.Text + "' AND SLIDE = '" + txt_Calc_BULK_SLIDE.Text + "'");
int result = returnrow.Length;
DataRow dr = returnrow[0];
txt_Calc_BULK_BULK.Text = (dr["BULK"].ToString());
con.Close();
}
What I wanna do is, there are 15 table in my database that has same table structure but different data in it. I want to change the sql query that execute by selecting different VAT Number from the combobox.
Since all tables have the same structure, I recommend making one big table for them all and add a VAT Number column to it. Then, to set the values in your combobox, select distinct VAT Numbers from this table. Finally, add the a VAT Number condition to your query.
On a side note, use "Parameterized Query" instead of concatenating values to your query, this would help against SQL Injection Attacks.

how to create user define tables by ADO.net

A desktop-based software shall enable a user to create tables in a provided database as per requirement.
My problem is that ExecuteNonQuery treats only Data Manipulation Language.
What should i use for Data Definition Language, i.e to pass create command.
Thanks in advance :)
my code
3rd party edit
From the linked image
public void create(string name, int varchar_quantity, string rate)
{
con.Close();
string s = "Crate table anas('" + name + "' varchar ('"
+ varchar_quantity + "')" + rate + "' int);";
con.Open();
SqlCommand com = new SqlCommand(s, con);
com.ExecuteNonQuery();
}
You should be able to create tables with ExecuteNonQuery method.
From msdn documentation,
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
var conStr = "PUT YOUR CONNECTION STRING HERE";
using (var c = new SqlConnection(conStr))
{
c.Open();
var qry = "CREATE TABLE TEST(name varchar(30));";
using (var cmd = new SqlCommand(qry, c))
{
cmd.ExecuteNonQuery();
}
}

How to remove the double quotes variable in c#

My project has different SQL Server DataTable. I will bind the data from user request table. so got table name as
Example:
table = "MyTable"
How to write the SQL query for select the particular table.
con.open();
SqlAdaptor da = new SqlAdaptor ("select * from '" + table.replace(""", "\"")" + '")
cmd.ExecuteNonQuery();
My replace is not working so I hope to any one resolve my issue.
Just escape " character?1
table.Replace("\"", string.Empty);
Also you don't need single quotes for your table name. By the way if you get this table as an input, I will strongly suggest do some strong validation before you put it in your query or use a whitelist.
You didn't show us rest of your code but use using statement to dispose your connection and adapter objects.
1: Since it is an escape sequence character
You can also try
SqlAdaptor da = new SqlAdaptor ("Select * from " + table.Replace('"', ' ').Trim());
string table = "MyTable";
table.Replace('\"', ' '); //Or
table.Replace('\"',string.Empty);

Read Excel cell values with SSIS script task

I am trying to read an Excel file via a SSIS ScriptTask to check for certain cell values in that worksheet.
In the code example you can see that the strSQL is set to "H4:H4" to only read one cell. This cell can only have a true or false value.
Since I also need to check for a certain string value in B1 I wanted to extend this version.
string filePath = "c:\\test\\testBoolean.XLSX";
string tabName = "testSheet$";
string strSQL = "Select * From [" + tabName + "H4:H4]";
String strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ filePath + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\";";
OleDbConnection cn = new OleDbConnection(strCn);
int iCnt = 0;
OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSQL, cn);
DataSet ds = new DataSet();
objAdapter.Fill(ds, tabName);
DataTable dt = ds.Tables[tabName];
foreach (DataRow row in dt.Rows)
{
iCnt = iCnt + 1;
// some processing....
}
What I don't understand is why I get a boolean value with the above strSQL statement or with any statment containing the same row number like so:
string strSQL = "Select * From [" + tabName + "F4:H4]";
Debug-Output:
row.ItemArray[2] false object {bool}
But when I set a different range like this one:
string strSQL = "Select * From [" + tabName + "F1:H4]";
I loose the recognition of the bool value:
row.ItemArray[2] "FALSE" object {string}
I'd much rather like to use the bool value for other processing tasks.
How can I fix this in addition to also reading the B2 value?
Your connection string specified IMEX=1, which tells the driver to treat intermixed data types as text. (See the "Usage Considerations" section of the MSDN article Excel Connection Manager.)
Thus, when you specified a single row
string strSQL = "Select * From [" + tabName + "F4:H4]";
there was only one possible data type for the third column, and the driver was able to correctly infer it. However, when you specified multiple rows
string strSQL = "Select * From [" + tabName + "F1:H4]";
and any value in the range H1:H4 was not a bool, the driver translated all values in that column to strings.
Assuming that you do in fact have mixed data types in column H and only care about the values in two particular cells, the simplest solution is to query each cell individually. See Import a single Excel cell into SSIS for some ideas on how to do that.
I would clone most of the code to produce two separate SELECT statements to query the two different cells you are after with separate SQL statements.
Actually I would probably go further and shred the whole script into SSIS components e.g. Execute SQL Tasks or Data Flow Tasks.

How can I see the data of a SQL server database in c#, and where it's store?

I have a program written in c# visual studio 2008 with SQL server 2005 (.mdf) database.
Here is part of the code:
...
SqlCommandBuilder cb;
cb = new SqlCommandBuilder(dataAdapter);
String[] dataList =new String [8];
...
DataTable resultTable = new DataTable();
FillDataList(data);
dataAdapter = new SqlDataAdapter("insert into ProcessData values('" + dataList[0] + "','" + dataList[1] + "','" + dataList[2] + "','" + dataList[3] + "','" + dataList[4] + "','" + dataList[5] + "','" + dataList[6] + "','" + dataList[7]+"')", con);
dataAdapter.Fill(resultTable);
...
My questions are:
1) Where is the data I added in those lines stored?
2) Why is it that when I Right-Click with the mouse in the Server Explorer->Data Connections->Tables->ProcessData (my table's name)->"show Table Data", I don't see the data but just NULL in the columns, and how can i see the data there?
3) Why when I present this data in a DataGridView sometimes it shows the data and sometimes it doesn't?
Many Thanks!
Without seeing more info on the datalist object and its construction, it's impossible to say. However, you're using the Fill and SQLDataAdapter incorrectly. The FILL relies on the SQLDataAdapter having a SelectCommand property set, which is what your code is bunging the INSERT statement into (that's what the SQLDataAdapter's constructor does). So...your Fill returns nothing as there's no SELECT where there should be.
Your INSERT should be part of the dataadapter's InsertCommand, and you'll need to write a separate SELECT statement to get anything into your resultTable.
I think you need to read some basic documentation on ADO.NET before you write any more code. You're passing an INSERT statement to the SqlDataAdapter constructor, which takes a SELECT statement. You're using the Fill method of SqlDataAdapter where you should be using the Update method. You're building a SQL string with hard-coded values in it where you should be using SqlParameters with references to the DataTable Columns. And is the fact that your DataTable is called "data" but that SQL string is using indexed properties from "dataList" just a typo? Because if it is, DataTable doesn't have an indexed property.
Try doing it like this (you need to fill in the correct connection string though):
// Get the db connection
SqlConnection dbCon = new SqlConnection("connection string");
// Select the data from the database table into a DataSet (even if it's empty)
DataSet myData = new DataSet();
SqlDataAdapter dbAdapter = new SqlDataAdapter("select * from ProcessData", dbCon);
dbAdapter.Fill(myData);
myData.Tables[0].TableName = "ProcessData"; // Keeps the table name consistent for the DataMember property
// Use the command builder to add insert, delete, update commands to your adapter
// You must have a primary key on the table for these to work, though
SqlCommandBuilder dbComBuilder = new SqlCommandBuilder(dbAdapter);
dbAdapter.InsertCommand = dbComBuilder.GetInsertCommand();
dbAdapter.DeleteCommand = dbComBuilder.GetDeleteCommand();
dbAdapter.UpdateCommand = dbComBuilder.GetUpdateCommand();
// Bind the data set to the GridView for viewing / editing
yourGridControl.AutoGenerateColumns = true; // Optional, if you haven't manually added the columns
yourGridControl.DataSource = myData;
yourGridControl.DataMember = "ProcessData";
// Use the db adapter to update the database (by calling those commands) with
// changes made to the DataSet through the grid. This would go in a different
// form event, like a Save Button click.
dbAdapter.Update();
If you don't have a primary key in the ProcessData table, you can directly insert values using this command:
// Insert the data directly with a command
SqlCommand dbInsCommand = new SqlCommand("insert into ProcessData values (" + val1 + "," + val2 + ")", dbCon);
dbInsCommand.ExecuteNonQuery();

Categories

Resources