I have a database in ms-access and wanted to select from it,
I know my question is very simple but I couldn't find the solution for it
this is how I want to select:
public static void SearchRationCreatorName(string RationCreator)
{
string StrCon = System.Configuration.ConfigurationManager....
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbDataAdapter DataA = new OleDbDataAdapter
("Select * from tRations where tRations.RationCreator= [RationCreator]", Connection);
DataTable Dtable = new DataTable();
DataA.Fill(Dtable);
but instead of selecting one row it select all of records in that table
That didn't show up well in the comment.
I think you mean
"Select * from tRations where RationCreator= '"+RationCreator+"'"
The way you worded your title suggests you may want to use a string in place of a tablename but your code suggests otherwise. IF you wanted to know how to select from a dynamic table, let me know.
Also, this will select all rows that match rationcreator. If you only want one row, use:
"Select TOP 1 * from tRations where RationCreator= '"+RationCreator+"'"
with or without an ORDER BY predicate
Related
I have this code in C#, but I need it to select all columns EXCEPT the first column of the table (the identity column), so that when I insert the data into an identical table in a different database, the destination database assigns its own identity column values:
SqlCommand commandSourceData = new SqlCommand($"SELECT * FROM dbo.{tableName};", sourceConnection);
SqlDataReader reader = commandSourceData.ExecuteReader();
Is there a way to do this?
If you want a generic solution for every column in your database you can use this kind of code
public string GetColumnsWithoutIdentity(string tableName, SqlConnection con)
{
SqlDataAdapter da = new SqlDataAdapter($"SELECT * FROM dbo.{tableName} where 1=0", con);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
var cols = dt.Columns.Cast<DataColumn>().Where(x => !x.AutoIncrement).Select(x => x.ColumnName);
return string.Join(",", cols);
}
Now you can use the returned string to build an Sql statement without the autoincrement column.
Notice that this code is vulnerable to Sql Injection. You should be absolutely sure that the tableName parameter used to build the first query is not typed directly by your user. Let it choose from a whitelist (readonly) of predefined tables (and also this is not 100% safe)
Another drawback is the fact that you need to hit the database two times. Once to get the schema with the info about the AutoIncrement column and one to fill the datatable after that.
I'm using C# to link with an Access database I have. I added this database by using the Data Source Configuration Wizard in VS, and now there are a couple of queries I'm trying to run.
This is the query I'm having trouble with, I think it's having an issue with me trying to reference a combobox from inside the query.
SELECT DISTINCT Column2
FROM MyTable
WHERE Column1 = cboMyComboBox.Text
ORDER BY Column2
A sample of data in the MyTable
Column1 Column2
Male Bob
Female Jane
Male Jim
Male John
Female Jill
And lets say the value in cboMyComboBox is 'Male'
I'm trying to get the query to return 'Bob', 'Jim' and 'John'
I'm pretty new to this so I'm probably missing something completely obvious, and feel free to refer me to any guides on doing this properly. (It may have something to do with parameters...? Do i need to be passing something to this query?)
The error I'm receiving is "No value given for one or more required parameters"
string query = String.Format(
#"SELECT DISTINCT Column2 FROM MyTable
WHERE Column1 = '{0}' ORDER Y Column2", cboMyComboBox.Text);
Otherwise the sql query will try and literally match column1 to the string cboMyComboBox.Text as opposed to the data in it.
In complete form:
public DataTable dattab;
public void GetData()
{
//setup the parameters for connecting
string connString = #"";// You need to define you connection string here.
string query = String.Format(#"SELECT DISTINCT Column2 FROM MyTable WHERE Column1 = '{0}' ORDER Y Column2", cboMyComboBox.Text);
//Create the connection and commmand objects, then open a connection to the DB.
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
//Retrieve the data and fill the datatable
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dattab);
//Close off connections
conn.Close();
da.Dispose();
}
Figured it out - In the query properties there is an option to add parameters - I was able to add it here then pass the combobox value when i ran the query method:
tableAdapter.GetColumn1Data(cboMyComboBox.Text)
Here in the code I am trying to retrieve information from a database and store it in a table. In query i have used a variable to specify a table, i am doing so because i want to use this single piece of code to retrieve information from various tables based on which table name the variable "a" contain but when i am executing this it's throwing me an exception. please help...
MyOleDbConnection.Open();
string a = "login";
string query = string.Format("select Email,Username,PhoneNo,Department from '{1}' where Email='{0}'", editrecordtextBox.Text,a);
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter(query, MyOleDbConnection.vcon);
da.Fill(dt);
Note- this is just the part of the code, the exception is occuring in this code only.
Your code is in fact working correctly.
First of all, remove your single quotes around the table name. These mark a text, not an identifier or name.
I can imagine that login is a reseverd name you cannot use as plain text in your SQL. Depending on the database you can quote your tablename so it is recognizes as a name, not an reserved word.
For SQL-Server it would be done with [ and ]:
string query = string.Format("select Email,Username,PhoneNo,Department from [{1}] where Email='{0}'", editrecordtextBox.Text,a);
If you would give us your database, we could help.
the way that tested and Worked is something like Below as you see the Table Name is Variable Form i Make a query with concatenate 3 section together
string query = "SELECT TOP 1 * FROM M" + TableName.ToString() + " ORDER BY ID
DESC";
In a C# 2.0 I have a list of fields and a list of values (stored as strings), a table name, and an ODBC Connection.
I need to get the data types of the fields that are on that table, so I know how to generate my sql.
What's the best way to get that information from what I've got?
My only idea is to do a SELECT TOP 0 * FROM #TableName in a data adapter, get back a dataset, and iterate through the list of field names against the datacolumn's in the datatable.
Is there any better way to go about this?
Try this
select * from sys.columns where object_id = object_id('MyTable')
Hope this helps.
You're best option is to query your datbases system tables like Nick Beradi mentioned. If that's not an option for whatever reason, you can do something like this:
using (SqlConnection conn = new SqlConnection(myConnectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * from MyTable", conn))
{
DataTable table = new DataTable();
adapter.FillSchema(table, SchemaType.Mapped);
//at this point, table will have no rows, but will have all the columns of which you can get their datatypes
}
}
I read an excel sheet into a datagrid.From there , I have managed to read the grid's rows into a DataTable object.The DataTable object has data because when I make equal a grid's datasource to that table object , the grid is populated.
My Problem : I want to use the table object and manipulate its values using SQL server,(i.e. I want to store it as a temporary table and manipulate it using SQL queries from within C# code and , I want it to return a different result inte a grid.(I don't know how to work with temporary tables in C#)
Here's code to execute when clicking button....
SqlConnection conn = new SqlConnection("server = localhost;integrated security = SSPI");
//is connection string incorrect?
SqlCommand cmd = new SqlCommand();
//!!The method ConvertFPSheetDataTable Returns a DataTable object//
cmd.Parameters.AddWithValue("#table",ConvertFPSheetDataTable(12,false,fpSpread2_Sheet1));
//I am trying to create temporary table
//Here , I do a query
cmd.CommandText = "Select col1,col2,SUM(col7) From #table group by col1,col2 Drop #table";
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText,conn);
DataTable dt = new DataTable();
da.Fill(dt); ***// I get an error here 'Invalid object name '#table'.'***
fpDataSet_Sheet1.DataSource = dt;
//**NOTE:** fpDataSet_Sheet1 is the grid control
Change your temp table from #table to ##table in both places.
Using ## means a global temp table that stays around. You'll need to Drop it after you have completed your task.
Command = " Drop Table ##table"
Putting the data into a database will take time - since you already have it in memory, perhaps LINQ-to-Objects (with DataSetExtensions) is your friend? Replace <int> etc with the correct types...
var query = from row in table.Rows.Cast<DataRow>()
group row by new
{
Col1 = row.Field<int>(1),
Col2 = row.Field<int>(2)
} into grp
select new
{
Col1 = grp.Key.Col1,
Col2 = grp.Key.Col2,
SumCol7 = grp.Sum(x => x.Field<int>(7))
};
foreach (var item in query)
{
Console.WriteLine("{0},{1}: {2}",
item.Col1, item.Col2, item.SumCol7);
}
I don't think you can make a temp table in SQL the way you are thinking, since it only exists within the scope of the query/stored procedure that creates it.
If the spreadsheet is a standard format - meaning you know the columns and they are always the same, you would want to create a Table in SQL to put this file into. There is a very fast way to do this called SqlBulkCopy
// Load the reports in bulk
SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString);
// Map the columns
foreach(DataColumn col in dataTable.Columns)
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
bulkCopy.DestinationTableName = "SQLTempTable";
bulkCopy.WriteToServer(dataTable);
But, if I'm understanding your problem correctly, you don't need to use SQL server to modify the data in the DataTable. You c an use the JET engine to grab the data for you.
// For CSV
connStr = string.Format("Provider=Microsoft.JET.OLEDB.4.0;Data Source={0};Extended Properties='Text;HDR=Yes;FMT=Delimited;IMEX=1'", Folder);
cmdStr = string.Format("SELECT * FROM [{0}]", FileName);
// For XLS
connStr = string.Format("Provider=Microsoft.JET.OLEDB.4.0;Data Source={0}{1};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'", Folder, FileName);
cmdStr = "select * from [Sheet1$]";
OleDbConnection oConn = new OleDbConnection(connStr);
OleDbCommand cmd = new OleDbCommand(cmdStr, oConn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
oConn.Open();
da.Fill(dataTable);
oConn.Close();
Also, in your code you ask if your connection string is correct. I don't think it is (but I could be wrong). If yours isn't working try this.
connectionString="Data Source=localhost\<instance>;database=<yourDataBase>;Integrated Security=SSPI" providerName="System.Data.SqlClient"
Pardon me, if I have not understood what you exactly want.
If you want to perform SQL query on excel sheet, you could do it directly.
Alternatively, you can use SQL Server to query excel (OPENROWSET or a function which I dont remember right away). Using this, you can join a sql server table with excel sheet
Marc's suggestion is one more way to look at it.
Perhaps you could use a DataView. You create that from a DataTable, which you already have.
dv = new DataView(dataTableName);
Then, you can filter (apply a SQL WHERE clause) or sort the data using the DataView's methods. You can also use Find to find a matching row, or FindRows to find all matching rows.
Some filters:
dv.RowFilter = "Country = 'USA'";
dv.RowFilter = "EmployeeID >5 AND Birthdate < #1/31/82#"
dv.RowFilter = "Description LIKE '*product*'"
dv.RowFilter = "employeeID IN (2,4,5)"
Sorting:
dv.Sort = "City"
Finding a row: Find the customer named "John Smith".
vals(0)= "John"
vals(1) = "Smith"
i = dv.Find(vals)
where i is the index of the row containing the customer.
Once you've applied these to the DataView, you can bind your grid to the DataView.
Change the command text from
Select col1,col2,SUM(col7) From #table group by col1,col2
to
Select col1,col2,SUM(col7) From ##table group by col1,col2