MySQL Connector: parameters not being added - mysql

Looking at my query log for MySQL, I see my parameters aren't being added. Here's my code:
MySqlConnection conn = new MySqlConnection(ApplicationVariables.ConnectionString());
MySqlCommand com = new MySqlCommand();
try
{
conn.Open();
com.Connection = conn;
com.CommandText = String.Format(#"SELECT COUNT(*) AS totalViews
FROM pr_postreleaseviewslog AS prvl
WHERE prvl.dateCreated BETWEEN (#startDate) AND (#endDate) AND prvl.postreleaseID IN ({0})"
, ids);
com.CommandType = CommandType.Text;
com.Parameters.Add(new MySqlParameter("#startDate", thisCampaign.Startdate));
com.Parameters.Add(new MySqlParameter("#endDate", endDate));
numViews = Convert.ToInt32(com.ExecuteScalar());
}
catch (Exception ex)
{
}
finally
{
conn.Dispose();
com.Dispose();
}
Looking at the query log, I see this:
SELECT COUNT(*) AS totalViews
FROM pr_postreleaseviewslog AS prvl
WHERE prvl.dateCreated BETWEEN (#startDate) AND (#endDate) AND prvl.postreleaseID IN (1,2)
I've used the MySQL .NET connector on countless projects (I actually have a base class that takes care of opening these connections, and closing them with transactions, etc.). However, I took over this application, and here I am now.
Thanks for the help!

Try like this.
mySqlCommand.Parameters.Add("#CustomerID", SqlDbType.NChar, 5);
mySqlCommand.Parameters["#CustomerID"].Value = "T1COM";

Some SQL clients, especially for MySql use "?" instead of "#".

Related

Displaying records of a particular month in mysql

I am trying to fetch records of a particular month from the database and the pattern of the data that column is ""
Query I am using is
select * from table_name WHERE column_name LIKE ''
for the month of September. But this is printing no results.
Please suggest.
Use direct date comparisons! Don't treat dates as strings. So something like:
where column_name >= '2000-09-01' and column_name < '2000-10-01'
Or, if you want all months, then extract the month. The standard function is extract():
where extract(month from column_name) = 9
or:
where month(column_name) = 9
However, the particular function depends on the database (not all databases support all the standard functions).
Building up on the answers and comments above. It seems like you want to use this in your C# code with the user selecting a value from a dropdown. One option would would be something like this:
string monthNumber = valueFromDropdown;
string connectionString = "put you connection string here";
string commandText = "select * from table_name "
+ "where month(column_name) = #MonthNumber";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#MonthNumber", SqlDbType.Int);
command.Parameters["#MonthNumber"].Value = monthNumber;
try
{
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

How to execute multiple statement with variables in C# OdbcCommand object

I want to execute below MySql queries at a time through OdbcCommand object within C# as dynamic query, it always fails:
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
set #row=0;
select * from
(
select #row:=#row+1 as my____row_num,
cities.`cityid`,
cities.`cityname`,
cities.`countryid`,
cities.`countryname` , '1' as my____data_row_created , '1' as
my____data_row_updated from `cities` ) p
where my____row_num>=101 and my____row_num<=200;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
I'm using below method to execute above MySql queries:
ExcuteCommand(Sql)
{
DataTable dt = new DataTable();
OdbcCommand SQLCommand = new OdbcCommand(Sql);
OdbcConnection Con = new OdbcConnection(ConnectionString);
try
{
Con.Open();
SQLCommand.Connection = Con;
OdbcDataAdapter da = new OdbcDataAdapter(SQLCommand);
da.Fill(dt);
Con.Close();
Con.Dispose();
}
catch
{
try
{
Con.Close();
}
catch { }
throw;
}
return dt;
}
I found solution from here. While executing multiple dynamic MySql statements through ODBC in C# we have two options:
Execute separately every command
Use stored procedures
In my case I'm bound to use dynamic-quires because I'm having only read-access on database.
Solution:
Rather than Declaring variable and set it, I used another technique to use a session variable as a derived table and crossed join it with the main table. See the following query, in my scenario I changes to below MySql query code and removed both SET SESSION related code from the query, and it worked properly:
select * from
(
select #row:=#row+1 as my____row_num,
cities.`cityid`,
cities.`cityname`,
cities.`countryid`,
cities.`countryname` , '1' as my____data_row_created , '1' as
my____data_row_updated from `cities` ,(select #row:=0) as t ) p
where my____row_num>=101 and my____row_num<=200;
I'm not going to attempt to solve your MySQL problem, but your C# code can and should be written better, and since comments are not suited for codes, I thought I'd better write this as an answer.
So here is an improvement to your C# part:
DataTable FillDataTable(string sql)
{
var dataTable = new DataTable();
using(var con = new OdbcConnection(ConnectionString))
{
using(var command = new OdbcCommand(sql, con))
{
using(var dataAdapter = new OdbcDataAdapter(SQLCommand))
{
dataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
Points of interests:
I've renamed your method to a more descriptive name. ExecuteCommand doesn't say anything about what this method does. FillDataTable is self explanatory.
The using statement ensures the disposing of instances implementing the IDisposable interface - And almost all ADO.Net classes are implementing it.
The disposing of an OdbcConnection also close it, so you don't need to explicitly close it yourself.
There is no point of catching exceptions if you are not doing anything with them. The thumb rule is to throw early, catch late. (actually catch as soon as you can do something about it like write to log, show a message to the user, retry etc').
DataAdapters implicitly opens the Connection object, no need to explicitly open it.
Other two improvements you can do are:
Have this method also accepts parameters.
Have this method also accept the CommandType as a parameter (currently, using a stored procedure with this will not work since the default value of CommandType is Text
So, an even better version would be this:
DataTable FillDataTable(string sql, CommandType commandType, params OdbcParameter[] parameters)
{
var dataTable = new DataTable();
using(var con = new OdbcConnection(ConnectionString))
{
using(var command = new OdbcCommand(sql, con))
{
command.CommandType = commandType;
command.Parameters.AddRange(parameters);
using(var dataAdapter = new OdbcDataAdapter(SQLCommand))
{
dataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
If you want to improve that even further, You can have a look at my GitHub ADONETHelper project - There I have a single private method for Execute, and the methods for filling data tables, filling data sets, execute non query etc' all use this single method.
would you please try this instead
declare #row int
set #row=0;
select * from
(
select SUM(#row,1) as my____row_num,
cities.cityid as CityID,
cities.cityname as CityName,
cities.countryid as CountryID,
cities.countryname as CountryName ,
'1' as my____data_row_created , '1' as my____data_row_updated from cities) //i did not understand the meaning of this
where (my____row_num BETWEEN 100 AND 200 )
backEnd
ExcuteCommand(Sql)
{
<AddThis>ConnectionString= ConfigurationManager.ConnectionStrings["YourDataBaseLocation_OR_theConnectionCreatedViaProperties"].Connectionstring;</AddThis>
DataTable dt = new DataTable();
<deleteThis> OdbcCommand SQLCommand = new OdbcCommand(Sql);</deletethis>
//You Need to add the connection you have used it and Odbc
//Command.CommandType= CommandType.StoredProcedure();
OdbcConnection Con = new OdbcConnection(ConnectionString);
<AddThis>OdbcCommand SqlCommand = new OdbcCommand(Sql,Con);</AddThis>
try
{
Con.Open();
SQLCommand.Connection = Con;
OdbcDataAdapter da = new OdbcDataAdapter(SQLCommand);
da.Fill(dt);
<add this > SQLCommand.ExecuteNonQuery();</Add this>
Con.Close();
<delete> Con.Dispose();</delete>
}
catch
{
try
{
Con.Close();
}
catch (Exception e) { }
throw (e);
}
return dt;
}

Microsoft Jet OLEDB syntax error on UPDATE

I have a database similar to the one below:
Table1(AutoNumber, Text, Number, Memo) // this is field types
Table1(ID, Title, Price, Image)
I'm trying to update an existing element of the database in C# using:
const string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=bd.mdb";
OleDbConnection m_dataBase = new OleDbConnection(connectionString);
OleDbConnection m_dataBase.Open();
SQL = "UPDATE Table1 SET Title='test', Price=35, Image='Test' WHERE ID=1";
OleDbCommand SQLQueryCommand = new OleDbCommand(SQL, m_dataBase);
int response = SQLQueryCommand.ExecuteNonQuery();
As a result I am getting this error. "Microsoft JET Database Engine Error syntax in UPDATE instruction".
What am I doing wrong?
PS: I can successfully do SELECT or INSERT, but not UPDATE.
Well, if your SQL command is the only problem, there are some visible issues.
Simply try to parametrize your Update clause using such as below which will prevent lots of little mistakes and also an SQL injection.
SQL = "UPDATE Table1 SET Title=?, Price=?, Image=? WHERE ID=?";
SQLQueryCommand.Parameter.Add("#MyTitle", OleDbType.VarChar).Value = "Test";
SQLQueryCommand.Parameter.Add("#MyPrice", OleDbType.Integer).Value = 35;
SQLQueryCommand.Parameter.Add("#MyImage", OleDbType.VarChar).Value = "TestAgain";
SQLQueryCommand.Parameter.Add("#MyID", OleDbType.VarChar).Value = 1;
To learn more about parametrization try having a look at the example in the bottom of this MSDN article.
OleDbCommand.Parameters Property
Also, it's a good practice to surround your connection inside a using statement.
using (var m_dataBase = new OleDbConnection(connectionString) { ... }

MySqlClient: SaveChanges in ASP.NET doesn't update DB table

I'm using MySql database in ASP.NET MVC 4 project with MySqlClient (MySQL Connector .NET ).
In the References are dlls: MySql.Data, MySql.Data.Entry, MySql.Web
Selects from MySql database executes successfully, but inserts and updates are doesn't executes. No errors, no exceptions.
code №1:
var connectionString = "Server=my_server;Uid=my_login;Pwd=my_password;Old Guids=true;persist security info=True;database=clientest;allow zero datetime=True;convert zero datetime=True";
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
String commandText = "update testdb.visit set doctor_spec='dentist' where visit_id = 2;";
MySqlCommand cmd = new MySqlCommand(commandText, conn);
cmd.CommandType = System.Data.CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
}
No errors, no exception, but the table hasn't updates
code №2
using (var db = new MySqlDBEntities())
{
var vx = (from v in db.visit where v.visit_id == 1 select v).FirstOrDefault();
vx.doctor_spec = "dentist";
db.SaveChanges();
}
No errors, no exception, but the table hasn't updates.
What's wrong? Maybe another way for using MySql in ASP.NET MVC projects?
P.S. Sorry for my poor English :(
check connection in web config and find Correctly Data File
After Do Save Change Successfully any Edited Or New Entity Changes is Update
check this code too
* from v in db.visit /* db.visits */ where *

MySqlDataReader.Read() "Timeout" when read from a very big table (over 100 million records)

I have a big table which contains about 100 million records in MySQL.
I want to read all the records from it and process them in my C#/.Net program,
so I wrote some code like this:
string sql = "SELECT * FROM the_table";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//...
}
But after running for 3 minutes, a timeout problem occurs.
If I change the SQL statement to use "limit":
string sql = "SELECT * FROM the_table limit 60000000" //60 million
then it works OK. (the loop while (rdr.Read()) took about 3.8 minutes)
Was the timeout caused because the table was too big?
What's going on here and how do I fix the problem?
OK, I finally localized the problem! It was because I used ""ADO.NET Driver for MySQL (Connector/Net)
which was developed by MySQL. And there may be some bugs. Then I change to use dotConnect , the problem was gone. Thank for all help.
I have set command timeout to a higher value and it fixed the issue.
MySqlCommand mySqlCommand = new MySqlCommand(sql_cmd);
mySqlCommand.Connection = _connection;
mySqlCommand.CommandTimeout = 3600;
Hope this helps