c# help with building where clause to query - string

i am newbie in c#,
i want to build query string , i do some conditions , every condition add another condition to where clause
i want something like that :
// BUILD SELECT QUERY
string where = "";
string[] where_arr = new string[];
if (condition1)
{
where_arr[index++] = " field = 5 ";
}
if (condition2)
{
where_arr[index++] = " field2 = 7 ";
}
if (where_arr.Count>0)
where = " where" + String.Join(" and ", where_arr);
string sql = "select count(*) as count from mytable " + where;
but i do not know exactly how to declare all the variables like where_arr

// BUILD SELECT QUERY
string where = "";
List<string> where_arr = new List<string>();
if (condition1)
{
where_arr.Add(" field = 5 ");
}
if (condition2)
{
where_arr.Add(" field2 = 7 ");
}
if (where_arr.Count > 0)
where = " where" + String.Join(" and ", where_arr.ToArray());
string sql = "select count(*) as count from mytable " + where;

Related

Load data into multiple excel sheets depending on conditions dynamically

I have a situation please help me out. I have to create multiple sheet in one excel file with different queries. Like i have to check if the particular column is null then the record against this query should be in excel file in new sheet and i have to check another column with other name if it is null or empty and then create a sheet for it and sheet should be created only if the query returns some result otherwise there should not be any empty sheet. i have 8 different columns to check .
For Example I have to execute following query which will be in source
SELECT DISTINCT AgencySourceSystemCode,SourceAgencyID,ProgramCode,PolicyNumber,EffectiveDate,AgencyName
FROM POL.vw_PolicyPremiumData
WHERE AgencyName IS NULL OR AgencyName = ''
And Sample result is
AgencySourceSystemCode SourceAgencyID
ProgramCode PolicyNumber
EffectiveDate AgencyName
GEN 1050- CAB DN17000008
2010-06-10 NULL
GEN 1050- CAB DN17000008
2011-06-10 NULL
GEN 1050- CAB DN17000008
2012-06-10 NULL
GEN 1050- CAB DN17000010
2010-06-10 NULL
GEN 1050- CAB DN17000010
2012-06-10 NULL
GEN 1050- CAB DN17000012
2010-06-22 NULL
GEN 1050- CAB DN17000012
2011-06-22 NULL
Here Agency Name is NULL like this i will have source query where Effective can be null .
I used this code snippet to create dynamic Excel file sheets .
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace ST_db9b6187d17c4dc99314d6ccb6ee7b08
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
string query = string.Empty;
string FileName = string.Empty;
string TableName = string.Empty;
string connstring = string.Empty;
string FolderPath = string.Empty;
string where = string.Empty;
string PackageName = "Error";
int SourceId = 0;
int BatchId = 0;
int flag = 0;
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
FolderPath = Dts.Variables["$Package::TempFolderPath"].Value.ToString();
FolderPath = FolderPath+"\\";
//if (FolderPath.LastIndexOf("\\")="\\")
//{
// FolderPath = Dts.Variables["$Package::TempFolderPath"].Value.ToString();
//}
if (File.Exists(FolderPath + PackageName + "File.XLSX"))
{
File.Delete(FolderPath + PackageName + "File.XLSX");
}
if (FolderPath.Contains(".xlsx"))
{
FolderPath = FolderPath.Trim('\\');
FolderPath = FolderPath.Remove(FolderPath.LastIndexOf('\\') + 1);
}
//USE ADO.NET Connection from SSIS Package to get data from table
string con = Dts.Connections["oledb_conn"].ConnectionString.ToString();
OleDbConnection _connection = new OleDbConnection(con);
OleDbCommand cmd = new OleDbCommand();
//Read distinct error euerries
query = "select distinct ErrorQuery, SheetName from ErrorMapping where FileType = 'PremiumFile'";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
cmd.CommandText = query;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorMapping = new DataTable();
dt_ErrorMapping.Load(cmd.ExecuteReader());
_connection.Close();
if (dt_ErrorMapping != null && dt_ErrorMapping.Rows.Count > 0)
{
foreach (DataRow dt_ErrorMapping_row in dt_ErrorMapping.Rows)
{
query = dt_ErrorMapping_row["ErrorQuery"].ToString();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 0;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorInfo = new DataTable();
dt_ErrorInfo.Load(cmd.ExecuteReader());
_connection.Close();
if (dt_ErrorInfo != null && dt_ErrorInfo.Rows.Count > 0)
{
Error(dt_ErrorMapping_row["SheetName"].ToString());
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::TempFolderPath"].Value.ToString() + "\\" +
"Error" + datetime + ".log"))
{
sw.WriteLine("Error Message: " + exception.Message.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
public void ExportExcelFile(DataSet ds, string connstring, string SheetName)
{
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Cmd.CommandTimeout = 0;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table [" + SheetName + "] (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
Excel_OLE_Con.Close();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
bool firstRow = true;
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into [" + SheetName + "] (" + sqlCommandValue + ") VALUES(";
int columnCount = table.Columns.Count;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.CommandTimeout = 0;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i].ToString() + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
}
}
public void Error(string ActualSheetName)
{
//USE ADO.NET Connection from SSIS Package to get data from table
string con = Dts.Connections["oledb_conn"].ConnectionString.ToString();
OleDbConnection _connection = new OleDbConnection(con);
OleDbCommand cmd = new OleDbCommand();
//drop Excel file if exists
if (!string.IsNullOrEmpty(ActualSheetName))
{
//FileType='PremiumFile'"
query = "Select ErrorQuery,SheetName,FileType from pol.ErrorMapping Where SheetName = '" + ActualSheetName + "' and FileType='PremiumFile'";
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 0;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorInfo = new DataTable();
dt_ErrorInfo.Load(cmd.ExecuteReader());
//cmd.ExecuteNonQuery();
_connection.Close();
if (dt_ErrorInfo != null && dt_ErrorInfo.Rows.Count > 0)
{
foreach (DataRow dt_ErrorInfo_row in dt_ErrorInfo.Rows)
{
query = dt_ErrorInfo_row["ErrorQuery"].ToString();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
//cmd.CommandTimeout = 600;
cmd.Connection = _connection;
cmd.CommandTimeout = 0;
_connection.Open();
DataTable dt_Actual_data = new DataTable();
dt_Actual_data.Load(cmd.ExecuteReader());
//cmd.ExecuteNonQuery();
_connection.Close();
FileName = PackageName + dt_ErrorInfo_row["FileType"].ToString();
//TableName = "ErrorFileInfo ";
//Construct ConnectionString for Excel
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + FileName + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
string SheetName = "";
object[] array = dt_ErrorInfo_row.ItemArray;
SheetName = array[1].ToString();
//Load Data into DataTable from SQL ServerTable
//string queryString = "SELECT * from " + TableName + " ";
//OleDbDataAdapter adapter = new OleDbDataAdapter(query, _connection);
DataSet ds = new DataSet();
ds.Tables.Add(dt_Actual_data);
//adapter.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ExportExcelFile(ds, connstring, SheetName);
flag++;
}
}
}
}
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}

Android Studio SQLite string comparison

I want to compare the date from a calendarView (year-month-day) to a date stored in a database. The problem is that, while they look the same, the query does not return anything from the db.
This is the date i insert into it:
Calendar calendar = Calendar.getInstance();
String mDay = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
String mMon = Integer.toString(calendar.get(Calendar.MONTH) + 1);
String mYear = Integer.toString(calendar.get(Calendar.YEAR));
String formattedDate = mYear + "-" + mMon + "-" + mDay;
contentValues.put(COL1, item);
contentValues.put(COL2, time);
contentValues.put(COL3, formattedDate);
It looks like this : 2019-12-5 (from log)
And this is the date i'm getting from the calendarView:
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
mDatabaseHelper = new DatabaseHelper(getContext());
String dom = Integer.toString(dayOfMonth);
String mo = Integer.toString(month + 1);
String ye = Integer.toString(year);
String date = ye + "-" + mo + "-" + dom;
Cursor data = mDatabaseHelper.getData(date);
It also looks like this: 2019-12-5 (taken from log)
And here is where i query the table:
public Cursor getData(String date){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL3 + "=" + date;
Cursor data = db.rawQuery(query,null);
return data;
}
The query doesn't return anything.
When i try to query only the day of month it works.
Your issue is that you aren't enclosing the date in single quotes, it is therefore taken as an arithmetic expression resulting in 2019 - 12 - 05 = 2002.
Instead of :-
public Cursor getData(String date){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL3 + "=" + date;
Cursor data = db.rawQuery(query,null);
return data;
}
Use either :-
public Cursor getData(String date){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL3 + "=?";
Cursor data = db.rawQuery(query,new String[]{date});
return data;
}
This properly escapes/encloses the date in single quotes) and in doing so protects against SQLInjection.
or instead use :-
public Cursor getData(String date){
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_NAME,null,COL3+"=?,new String[]{date},null,null,null);
}
This uses the query convenience method (this being the typically recommended solution). This also properly encloses strings in quotes and protects against SQL Injection as well as generating the SQL on your behalf and is therefore less prone to mistakes.
I hope this helps as I've got a filter system using a SQL database and then checking that data by a input from the user.
First thing to note is in my database I store the date as a string.
When I add the date I do it like so:
date = calendar.getTime().toString();
Then I need to get the time for the user this is done via:
private Calendar Start_filter_String;
private Calendar Stop_filter_String;
private Calendar database_cal;
String parse_string_start;
String parse_string_stop;
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
parse_string_start = "Mon"+ " "
+Month_Spinner_value+" "
+Day_Spinner_value +" "
+Hour_Spinner_value +":"
+Minute_Spinner_value+":"
+"00"+" "+"GMT"+" "
+Year_Spinner_value;
Start_filter_String.setTime(sdf.parse(parse_string_start));
Then this code below check the time you pass in. Note my SQL database is done via a cursor to data. Also my time string is stored in column 8.
try {
database_cal.setTime(sdf.parse(data.getString(8)));
} catch (ParseException e) {
e.printStackTrace();
}
if(Start_filter_String.compareTo(database_cal) == 1)
{
Log.d(TAG, "Filter: Data is not after start time");
}
if(Stop_filter_String.compareTo(database_cal) == 1)
{
Log.d(TAG, "Filter: Data is not before stop time");
}
if(Start_filter_String.compareTo(database_cal) == -1)
{
Log.d(TAG, "Filter: Data is after start time");
}
if(Stop_filter_String.compareTo(database_cal) == -1)
{
Log.d(TAG, "Filter: Data is before stop time");
}
Hope this helps

How to Write SQL Query Results into excel using Selenium Web Driver +Test NG

How do i write SQL Query Results into excel using Selenium Web Driver + Test NG
Example :
#Test(priority=5)
public void VerifyDataBase() {
try {
String query = "SELECT * FROM [xxx].[dbo].[xxx_FEINProductionCompany] where ProductionCompanyName like'%xxx%'";
System.out.println(query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next()) {
int FEIN_ID = rs.getInt("ACA_FEINProductionCompany_ID");
int FEIN_No = rs.getInt("FEIN");
String ProductionCompanyName = rs.getString("ProductionCompanyName");
String ProductionCompanyShortName = rs.getString("ProductionCompanyShortName");
String ModifiedDate = rs.getString("ModifiedDate");
String Username = rs.getString("Username");
String AddressLine1 = rs.getString("AddressLine1");
String AddressLine2 = rs.getString("AddressLine2");
String City = rs.getString("City");
String State = rs.getString("State");
int Zip = rs.getInt("Zip");
String PhoneNumber = rs.getString("PhoneNumber");
String ContactName = rs.getString("ContactName");
String ContactPhone = rs.getString("ContactPhone");
System.out.println("\nProductionCompanyName is: " + ProductionCompanyName);
System.out.println("\nFEIN is: " + FEIN_No);
System.out.println("\nAddressLine2 is: " + AddressLine2);
System.out.println("\nUsername is: " + Username);
TestUtil.assertEquals(Username, "xxxx","FEINScreen_Username");
TestUtil.assertEquals(AddressLine2, "2500 xx","FEINScreen_AddressLine2");
System.out.println("\nQuery Result Set is: "+ ProductionCompanyName+"\t"+FEIN_No+"\t"+AddressLine2+"\t"+Username);
System.out.println("\t");
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
You need to use java library/dependencies like apache poi.
Selenium or TestNG do not have any capability to interact with Excel.
use below link code and pass your sql query data to in it as an Input parameter
Refer:
https://howtodoinjava.com/library/readingwriting-excel-files-in-java-poi-tutorial/

Update Excel Cell using OLEDB

I want to update 1 cell in an Excel (xlsx) file using OLEDB.
I have attached my code.
The first time you run, it fills in the values because INSERT is working.
The second time you run, it APPENDS the values because the UPDATE fails, and my Catch performs an INSERT. My goal is to have the UPDATE command work. When the UPDATE command executes, I get an error message:
No value given for one or more required parameters.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ConsoleApp3.Program.InsertCSVIntoSheet(String excelPath, String sheet, String csvPath) in C:\Users\jbendler.atlab\source\repos\ConsoleApp3\Program.cs:line 175
This code comes from a demo Console App. This is the program.cs file.
The main part of the code is located at the bottom of the InsertCSVIntoSheet method. The output xlsx file is simply a new workbook, unedited. The input file is simply a text file, named with a .csv extension, that contains the following separated by carriage-return/linefeed - so the file has 5 lines with one character per line:
ABCDE
Thanks.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
InsertCSVIntoSheet(#"c:\temp\book1.xlsx", "NewSheet", #"c:\temp\test.csv");
}
private static void InsertCSVIntoSheet(string excelPath, string sheet, string csvPath)
{
int column;
int row;
int pos;
bool done;
char readUntilChar;
string csvData;
string columnName;
string cell;
string excelSheetName;
List<Tuple<int, int, object>> values = new List<Tuple<int, int, object>>();
string connectionString = CreateOleDbConnectionStringForExcel(excelPath);
OleDbCommand oleDbCommand = new OleDbCommand();
decimal decimalTest;
DateTime dateTimeTest;
int status;
int numColumns;
// Put CSV in to row/column/value Tuples
using (StreamReader reader = new StreamReader(csvPath))
{
csvData = reader.ReadToEnd();
row = 1;
// Split the csv data by new line
foreach (string line in csvData.Split(new string[] { "\r\n" }, StringSplitOptions.None))
{
if (!string.IsNullOrEmpty(line))
{
column = 1;
pos = 0;
cell = string.Empty;
// Split each line by ',' to get each cell. A value wrapped in '"' can include a ','
while (pos < line.Length)
{
cell = string.Empty;
// Check the first character. If it is a '"' then we assume the cell is surrounded
// in '"' and do NOT include the '"' in the output to the excel cell.
if (line[pos] == '"')
{
readUntilChar = '"';
pos++;
}
else
{
readUntilChar = ',';
}
done = line[pos] == readUntilChar;
if (line[pos] == '"')
{
// Skip over second '"' for a blank ("")
pos++;
}
while (!done)
{
cell += line[pos++];
if (pos == line.Length || line[pos] == readUntilChar)
{
if (readUntilChar == '"')
{
// Skip the '"'
pos++;
}
done = true;
}
}
// Skip over the ','
pos++;
if (!string.IsNullOrEmpty(cell))
{
// Test the data to determine the type (check for decimal and DateTime).
if (decimal.TryParse(cell, out decimalTest))
{
values.Add(new Tuple<int, int, object>(row, column, decimalTest));
}
else if (DateTime.TryParse(cell, out dateTimeTest))
{
values.Add(new Tuple<int, int, object>(row, column, dateTimeTest));
}
else
{
// Write out the value as a string
values.Add(new Tuple<int, int, object>(row, column, cell));
}
}
column++;
}
}
row++;
}
}
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
{
excelSheetName = GetExcelSheetNames(connectionString).Where(n => n.ToUpper().StartsWith(sheet.ToUpper())).FirstOrDefault();
//Set the connection string to recognize the header and to operate in Update mode(IMEX= 0)
using (OleDbConnection oleDbConnection = new OleDbConnection(connectionString.Replace("IMEX=1", "IMEX=0")))
{
oleDbConnection.Open();
oleDbCommand = new OleDbCommand();
oleDbCommand.Connection = oleDbConnection;
oleDbCommand.CommandType = CommandType.Text;
if (excelSheetName != null)
{
// Delete Sheet
oleDbCommand.CommandText = "DROP TABLE [" + sheet + "]";
status = oleDbCommand.ExecuteNonQuery();
}
else
{
excelSheetName = sheet + "$";
}
numColumns = values.Max(v => v.Item2);
oleDbCommand.CommandText = "CREATE TABLE [" + sheet + "](";
for (int index = 0; index < numColumns; index++)
{
oleDbCommand.CommandText += "Column" + index.ToString() + " CHAR(255), ";
}
oleDbCommand.CommandText = oleDbCommand.CommandText.Substring(0, oleDbCommand.CommandText.Length - 2) + ")";
status = oleDbCommand.ExecuteNonQuery();
}
using (OleDbConnection oleDbConnection = new OleDbConnection(connectionString.Replace("IMEX=1", "IMEX=0")))
{
oleDbConnection.Open();
oleDbCommand.Connection = oleDbConnection;
// Write out new values
foreach (Tuple<int, int, object> tuple in values)
{
try
{
columnName = GetExcelColumnName(tuple.Item2) + (tuple.Item1 + 1).ToString();
oleDbCommand.CommandText = "UPDATE [" + excelSheetName + columnName + ":" + columnName + "] SET " + "F1" + " = '" + tuple.Item3.ToString() + "'";
status = oleDbCommand.ExecuteNonQuery();
}
catch (OleDbException oledbex)
{
oleDbCommand.CommandText = "INSERT INTO [" + excelSheetName + "] VALUES ('" + tuple.Item3.ToString() + "')";
status = oleDbCommand.ExecuteNonQuery();
}
}
}
}
}
private static List<string> GetExcelSheetNames(string connectionString)
{
OleDbConnection oleDbConnection = null;
DataTable dataTable = null;
List<string> excelSheetNames = null;
using (oleDbConnection = new OleDbConnection(connectionString))
{
oleDbConnection.Open();
dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
}
if (dataTable != null)
{
excelSheetNames = new List<string>(dataTable.Rows.Cast<DataRow>().Where(r => r["TABLE_NAME"].ToString().EndsWith("$") || r["TABLE_NAME"].ToString().EndsWith("$'")).Select(r => r["TABLE_NAME"].ToString().ToUpper()));
}
return excelSheetNames;
}
private static string CreateOleDbConnectionStringForExcel(string sourceFile)
{
var fileInfo = new FileInfo(sourceFile);
switch (fileInfo.Extension.ToUpper())
{
case ".XLS":
return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;;Data Source='{0}';Extended Properties='Excel 8.0;HDR=No;IMEX=1'", sourceFile);
case ".XLSX":
case ".XLSM":
return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;;Data Source='{0}';Extended Properties='Excel 12.0;HDR=No;IMEX=1'", sourceFile);
default:
throw new NotSupportedException("File type not supported.");
}
}
private static string GetExcelColumnName(int columnNumber)
{
string columnName = String.Empty;
int dividend = columnNumber;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}
}
}

Subsonic - Simple Query

I have a table has 2 columns
Val1 int
Val2 int
My query very simple.
I want to get collection of record have condition (val1=Val2) ,
equivalent to (Select * from table where Val1=Val2)
I try
IDataReader rdr = new Query("Table").WHERE("Val1=Val2").ExecuteReader();
tableColl.LoadAndCloseReader(rdr);
rdr.Close();
and
..WHERE (" 'Val1=Val2' ")
..WHERE (Table.Columns.Val1,IsEqualTo,Table.Columns.Val2) //This not reguler I know
..WHERE ("Val"+'='+"Val2")
.....
any help be more apricated.
Thanks.
Unfortunately you'll need to do this as an inline query as far as I know:
TableCollection tableCollection = new InlineQuery()
.ExecuteAsCollection<TableCollection>(
"SELECT * FROM " + Table.Schema.TableName " WHERE " + Table.Columns.Val1 + " = " + Table.Columns.Val2);
was in same situation recently and came up with this:
TableCollection tablecollection = new TableCollection;
Comparison comp = Comparison.Equals;
tablecollection.Where(Table.Columns.Val1, comp, Table.Columns.Val2);
tablecollection.Load();
i found this better because i don't like inline queries. and it gives
more flexibility if you wish to allow for adhoc querying in you app.
private void CreateDynamicControls()
{
panGvHolder.Controls.Clear();
Query qry = Northwind.Product.CreateQuery();
qry.Columns.AddRange(Northwind.Product.Schema.Columns);
qry.WHERE("UnitPrice > 15").AND("UnitsInStock < 20 ");
//WHERE("UnitPrice > 15").AND("UnitsInStock < 30 ");
using (IDataReader rdr = qry.ExecuteReader())
{
Response.Write("<table>");
while (rdr.Read())
{
Response.Write("<tr>");
for (int i = 0; i < rdr.FieldCount; i++)
{
Response.Write("<td>");
Response.Write(rdr[i].ToString() + " ");
Response.Write("<td>");
} //eof for
Response.Write("</br>");
Response.Write("</tr>");
}
Response.Write("<table>");
}
} //eof method

Resources