Conversion between Numeric and Double/Decimal in C# - c#

I'm trying to grab elements from a certain column/Listbox which has the type "numeric" and store them in a List in C#.
datTable = new DataTable();
sqlCmd = new SqlCommand(#
"SELECT DISTINCT [" + form1.getColumnName() + "]
FROM [" + form1.getTableName() + "]", connection);
sqlDatAdapter = new SqlDataAdapter(sqlCmd.CommandText, connection);
sqlDatAdapter.Fill(datTable);
form1.columnStorList.DisplayMember = form1.getColumnName();
form1.columnStorList.ValueMember = "Column1";
form1.costStorList.DataSource = datTable;
List<Decimal> columnElements = new List<Decimal>();
foreach (var selectedItem in form1.columnStorList.SelectedItems)
{
DataRow row = (selectedItem as DataRowView).Row;
columnElements.Add(row.Field<decimal>(form1.getColumnName()));
}
Somehow he don't want to convert it. Double doesn't work at all. For example the value '0,000000' gets displayed as '0'. I tried to convert the elements to Double but then I get '0.0'. Decimal should be the closest to Numeric or am I wrong? How to display it correctly?
I want to use a SELECT Statement (SELECT...FROM...WHERE...=0,000000) to search the value in the database when I highlight it in my Listbox. Since he cuts the values off that specific value won't get found in my database.
The SELECT Statement is:
datTable = new DataTable();
fullStatementColumn = Convert.ToString(columnElements[0]);
String selectStatement = "SELECT [" + form1.colBox.Text + "]
FROM [" + form1.tableNameVal.Text + "]
WHERE convert(varchar(120),[" + form1.getColumnName() + "])='"
+ fullStatementColumn + "'";

Related

Bringing Specific Date Record in MS access using C#

I want to bring a records of commission on specific date. Here is my code;
globalxx = 0;
string month1 = dateTimePicker2.Value.Month.ToString();
string day1 = dateTimePicker2.Value.Day.ToString();
string year1 = dateTimePicker2.Value.Year.ToString();
string s2 = "#" + month1 + "/" + day1 + "/" + year1 + "#";
DataTable results = new DataTable();
using (OleDbConnection conn = new OleDbConnection(xi))
{
OleDbCommand cmd = new OleDbCommand("select * from COMMISSION where DateCommission='" + s2 + "'", conn);
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#DateCommission", s2)
});
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
dataGridView2.DataSource = results;
But the problem is it gives error at
adapter.Fill(results);
saying: "OleDB Excpetion has been handeled Data type mismatch in criteria expression."
I Need help.
My MS Access Schema is:
DateCommission: Date Time
DriverName: TEXT
DriveVehicleNumber: TEXT
CommissionedPrice: NUMBER
I am not got at parameter.
Here is the front end of c#;
Front End
Handle your date as that, and then concatenate a formatted string expression in the SQL:
string textDate = dateTimePicker2.Value.ToString("yyyy'/'MM'/'dd");
string s2 = "#" + textDate + "#";
and then:
OleDbCommand cmd = new OleDbCommand("select * from COMMISSION where DateCommission = " + s2 + "", conn);
Or (preferred) use a parameter of data type DateTime which you pass Value of the datepicker directly.

Using Subquery as Parameter Value [duplicate]

Im trying to perform a parameterized query in SQLite from C#, and the method im using is along the lines of creating a static command with
SQLiteCommand cmd = new SQLiteCommand(
"SELECT [ID]" +
",[email]" +
",[serializedata]" +
",[restrictions]" +
" FROM " + UserTable +
" WHERE #search = #searchparam", SQLConnection);
cmd.Parameters.Add(new SQLiteParameter("#searchparam"));
cmd.Parameters.Add(new SQLiteParameter("#search"));
and calling it like this:
Command.Parameters["#searchparam"].Value = searchdata;
Command.Parameters["#search"].Value = search;
SQLiteDataAdapter slda = new SQLiteDataAdapter(UserSelectUsernameCommand);
DataSet ds = new DataSet();
slda.Fill(ds);
User[] array = new User[ds.Tables[0].Rows.Count];
int index = 0;
foreach (DataRow row in ds.Tables[0].Rows)
{
array[index] = new User(this, row);
index++;
}
return array;
but im getting an error along the line of " '#search' is not a correct column name " or something like that. if i use a constant column name, and only use the data for parameters it works, but i dont want to create 10 different commands for when i need to search by different column names.
What is the issue here?
Generally things like column names (or table names) can not be parameterised - and the fact that there are different indices means that it will have to be a different plan internally. So you will have to use concatenation - but be careful to white-list the known column names to prevent sql injection:
SQLiteCommand cmd = new SQLiteCommand(#"
SELECT [ID],[email],[serializedata],[restrictions]
FROM " + whiteListedUserTable + #"
WHERE [" + whiteListedColumnName + #"] = #searchparam", SQLConnection);
cmd.Parameters.Add(new SQLiteParameter("#searchparam"));
...
Command.Parameters["#searchparam"].Value = searchdata;
You cannot use a query parameter in that fashion -- to indicate a column name. You can only use it to supply values.
Consider something like this instead:
SQLiteCommand cmd = new SQLiteCommand(
"SELECT [ID]" +
",[email]" +
",[serializedata]" +
",[restrictions]" +
" FROM " + UserTable +
" WHERE [" + search + "] = #searchparam", SQLConnection);
cmd.Parameters.Add(new SQLiteParameter("#searchparam"));
If you control all of the input to this function and none if it can be supplied by someone other than you, this should be safe. But if search comes from an untrusted third party, be sure to make the appropriate security checks on the value.

Adding multiple TextBoxes in one column of database

I'm creating an Inventory System which can add multiple items in a single click. how could I do this? I can already save data but for just a single textbox.
//Add new Data if Item Code is not exit;
{
OleDbCommand cmdInsert = new OleDbCommand(#"insert into TblInventory (ItemCode,ProductName,Quantity,DateAndTime) values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "','" + time + "')");
cmdInsert.Connection = con;
cmdInsert.ExecuteNonQuery();
MessageBox.Show("You added New " + txtQuantity.Text + " " + txtProduct.Text + " in the list", "New Item");
}
con.Close();
assuming that I have another textBoxes which are txtItem2, txtProduct2 and txtQuantity2. where can I locate those on my insert into statement?
First, use parameters instead of string concatenation, like below:
OleDbCommand cmdInsert = new OleDbCommand(
#"insert into TblInventory (ItemCode,ProductName,Quantity,DateAndTime) values (#ItemCode,#ProductName,#Quantity,#DateAndTime)");
cmdInsert.Parameters.AddWithValue("ItemCode", txtItem.Text);
cmdInsert.Parameters.AddWithValue("ProductName", txtProduct.Text);
cmdInsert.Parameters.AddWithValue("Quantity", txtQuantity.Text);
cmdInsert.Parameters.AddWithValue("DateAndTime", time);
Second, if you need many inserts, use loop. Or, wrap your insert code in function with four parameters ItemCode,ProductName,Quantity,DateAndTime. Use them instead of direct references to txtSomething.Text values, i.e. (pseudocode):
InsertRecord(txtItem.Text, txtProduct.Text, ...);
InsertRecord(txtItem2.Text, txtProduduct2.Text, ...);
For loop you can write like below:
var rows = new[]
{
new {Item = "item1" /*value from txtItem1*/, Product = "product1", Quantity = "Quantity1" /*should be int?*/},
new {Item = "item2" /*value from txtItem2*/, Product = "product2", Quantity = "Quantity2"}
};
foreach (var row in rows)
{
OleDbCommand cmdInsert = new OleDbCommand(
#"insert into TblInventory (ItemCode,ProductName,Quantity,DateAndTime) values (#ItemCode,#ProductName,#Quantity,#DateAndTime)");
cmdInsert.Parameters.AddWithValue("ItemCode", row.Item);
cmdInsert.Parameters.AddWithValue("ProductName", row.Product);
cmdInsert.Parameters.AddWithValue("Quantity", row.Quantity);
cmdInsert.Parameters.AddWithValue("DateAndTime", DateTime.Now);
cmdInsert.Connection = conn;
cmdInsert.ExecuteNonQuery();
}
You could create a stored procedure accepting xml as input parameter, and then in the stored procedure ypu will parse the xml and insert the data to the table,

Read Data from .dbf File with OdbcConnection

I am using visual studio 2010 on Win 7. I want to read a .dbf file and get the minimum value of a selected column.
Here is what I have:
System.Data.Odbc.OdbcConnection oConn = new System.Data.Odbc.OdbcConnection();
oConn.ConnectionString = #"Driver={Microsoft dBase Driver (*.dbf)};SourceType=DBF;SourceDB=" + ImportDirPath + ";Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
oConn.Open();
// Update time
string nowTime = DateTime.Now.ToString("HHmmss");
oCmd.CommandText = #"UPDATE " + tableName + " SET HQCJBS = " + nowTime + " WHERE HQZQDM = ?";
oCmd.Parameters.AddWithValue("row2", "000000");
oCmd.ExecuteNonQuery();
string query = "SELECT MIN(" + colName + ") FROM " + tableName + " WHERE HQZQDM <> 000000";
OdbcDataAdapter da = new OdbcDataAdapter(query, oConn);
DataSet ds = new DataSet();
da.Fill(ds);
Suppose colName and tableName are correct. I have two question.
Two Questions:
When the code da.Fill(ds); is hit, I got an error data type mismatch in criteria expression access, What is wrong?
After I get the minimum value from the database, how can I input it into the memory as a double, for example double min = ds.Tables[0];
Your update command should apply TWO parameters... one for the set, another for the where clause. Use the "?" place-holder for each respectively and add the parameters in the same order as they appear in the query.
string nowTime = DateTime.Now.ToString("HHmmss");
oCmd.CommandText = #"UPDATE " + tableName + " SET HQCJBS = ? WHERE HQZQDM = ?";
oCmd.Parameters.AddWithValue("setParm", nowTime );
oCmd.Parameters.AddWithValue("whereParm, "000000");
oCmd.ExecuteNonQuery();
For your select MIN() query, it appears your WHERE criteria column is a string and by having the literal numbers without quotes is applying it as a numeric... Again, stick with "?" parameters
OdbcCommand getMinCmd = new OdbcCommand("", oConn);
getMinCmd.CommandText = "SELECT MIN(" + colName
+ ") FROM " + tableName + " WHERE HQZQDM <> ?";
getMinCmd.Parameters.AddWithValue("whereParm, "000000");
OdbcDataAdapter da = new OdbcDataAdapter(getMinCmd);
DataSet ds = new DataSet();
da.Fill(ds);
Finally, to get the value OUT of the retrieved query into memory, you need to get the row of the table (only 1 record result set, zero-based index) and column-0 too. Since you did not assign a column name, you don't know the column and just go with 0-index...
int lowestValue = (int)ds.Tables[0].Rows[0][0];
Think of the above as the hierarchy...
ds
tables[0]
rows[0]
[column 0]
rows[1] -- but your query would only have one row anyhow
[column 0]
tables[1] -- if your query had multiple queries, this might be available
but at least it shows where the pieces are.
Now, if you change your query slightly to something like
select MIN( colName ) as MyMinValue ...
then your reference would be where you explicitly name the column from the row retrieved
int lowestValue = (int)ds.Tables[0].Rows[0]["MyMinValue"];

How do i assign the return data from MySql to a C# variable?

I am trying to acquire the count of a column in my database.
string cmdstr = "select count(" + col + ") from " + tbname + " where \"" +
col + "\" =\"" + val + "\"";
However, I do not know how to assign the count value to an int.
var myVariable = new MySqlCommand("SELECT 3 FROM table WHERE id = 1",
databaseCon);
int id = (int)myVariable.ExecuteScalar();
Cast your teturn value and assign it to Int type variable
If you want more help inform me
Perhaps this is able to help you:
var result = Cmd.ExecuteNonQuery();
This was suggested to me on one of my SQL questions, when I asked as to why doing it like this rather then just typing Cmd.ExecuteNonQuery();. He explained to me that this way you get a variable saying how many rows were affected.
There is two way, ExecuteScalar to get the value or you can get DataSet
ExecuteScalar
int result = Convert.ToInt32(sqlCommand.ExecuteScalar().ToString());
DataSet
MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(sqlCommand);
DataSet dataSet = new DataSet();
mySqlDataAdapter.Fill(dataSet);
int result = Convert.ToInt32(DataSet.Tables[0].Rows[0]["YourFieldName"].Tostring());

Categories