Does some one know, how to use wildcards with ado.net parameter in sybase sql anywhere?
For example i want to search for all names, starting with Se. In a normal query i would use select * from names where name like 'Se%'. But in ADO.Net my query looks like SELECT * from names where name like ? and the question mark will be set over SAParameter.
SACommand command = new SACommand(SqlStatement, cConnection);
command.Parameters.Add(new SAParameter() { Value = "Se%" });
The problem is, Value could not contains any wildcards.
Thank you very much!
here's my solution example
using (SAConnection con = new SAConnection(DBConnStr))
{
con.Open();
try
{
string sql = "select * from names where name like ?";
SACommand cmd = new SACommand(sql, con);
cmd.Parameters.Add("#p1","Se%");
SADataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr["name"].ToString());
}
rdr.Close();
}
finally
{
con.Close();
}
}
Console.ReadLine();
Related
As mentioned above:
I'm using C# to connect to a MySQL database and I want to read JSON data type.
I use the method MySqlCommand.ExecuteReader:
using (MySqlConnection sconn = new MySqlConnection(sqlConnectString))
{
sconn.Open();
String sql_Command = #"SELECT `id` FROM orders.jsontest;";
using (MySqlCommand scmd = new MySqlCommand(sql_Command, sconn))
{
**MySqlDataReader sdr = scmd.ExecuteReader();** // fatal error
DataTable datatable = new DataTable();
// ...
}
}
Can it be that I cannot use ExecuteReader here?
I know this question is old, but just in case you do not yet have a solution to your problem or anyone else encounters a similar problem, the following code should work for you:
private IEnumerable<int> GetIds()
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT id FROM jsontest"; // Assuming that `orders` is your database, then you do not need to specify it here.
using (MySqlCommand command = new MySqlCommand(commandText, connection))
{
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
yield return reader.GetInt32(0);
}
}
}
}
Now what you should pay attention to is this line
while (reader.Read())
which fetches results from the jsontest table as long as the MySqlDataReader can still read valid results and this line
yield return reader.GetInt32(0);
which instructs the reader to get and return each record of the fetched table one at a time as an Int32 (int). You need to change this if your tables column type is not INT.
Since you selected just one column (i.e. "SELECT id"), the parameter is 0, because your fetched resul table consists of one column only.
Additionally, in your code you seem to want to get the results as a DataTable; if so, you should use MySqlDataAdapter instead of the MySqlDataReader as follows:
DataTable resultTable = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(table);
Correct your sql command
String sql_Command = #"SELECT id FROM orders.jsontest";
I want to select the items that matches with the entered string.It seems the query is selecting all items that contain at-least a matching letter.
I don't want exact match ..i want to select the strings that match the starting..Like if i type 'it' i want to list all strings that starts with 'it'
What im i doing wrong?
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "SELECT itemname,rate,stock FROM mytable WHERE itemname LIKE #id";
SqlCommand command = new SqlCommand(commandText, conn);
string searchParam = String.Format("%{0}%", text_item.Text);
command.Parameters.AddWithValue("#id", searchParam);
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Don't use LIKE but use =. And change your string be exact string, instead of %text%
string commandText = "SELECT itemname,rate,stock FROM mytable WHERE itemname = #id";
...
string searchParam = text_item.Text;
---------------------- EDITED ------------------------
After the updated question, the answer would be:
string searchParam = string.Format("{0}%", text_item.Text);
The first % is not necessary, because you don't want wildcard there.
Instead of "Like" you should use "=". Like is usually used if you want to search with wildcards.
If you want your query to return results starting with, change your parameter value to
string searchParam = String.Format("{0}%", text_item.Text);
Your code is running fine.
Yes, you can use LIKE operator in the query.
Kindly debug and check what's coming in the "text_item" variable.
Narrow your search.
You can refer the link
to check the syntax for like operator.
I'm trying to return a query (in a gridview in ASP.NET) WHERE Time >= DateTime.Now.Add(-60). The WHERE clause has been giving me no end of difficulties.
DateTime pastTime = DateTime.Now.Add(-60);
ds_DB.SelectCommand = "SELECT * FROM [vPurchaseTotals] WHERE [TimeOfTransaction] >= " + pastTime;
My issue is getting pastTime to convert properly, so it only returns the newer data. [TimeOfTransaction] is a time(7) data type in the table.
How do I parse C#'s DateTime to SQL Server's Time?
Here, try this:
using(SqlConnection conn = new SqlConnection(yourConnectionString))
{
DateTime pastTime = DateTime.Now.Add(-60);
ds_DB.SelectCommand = #"SELECT * FROM [vPurchaseTotals]
WHERE [TimeOfTransaction] >= #PastTime";
SqlCommand cm = conn.CreateCommand();
cm.CommandText = ds_DB.SelectCommand;
cm.Parameters.Add("#PastTime", SqlDbType.Time).Value = pastTime.TimeOfDay; //For comparison with TSQL TIME type
try
{
conn.Open();
// Do what you need to do here.
}
catch(SqlException e)
{
// Handle Exception
}
finally
{
conn.Close();
}
}
Just for future reference, you should always parameterize your queries. It ends up being a lot safer and cleaner/easier to read and adjust.
EDIT: Are you using a SqlDataAdapter class? Is that what ds_DB is an instance of? I would personally just use a string value for your query and then implement the SqlDataAdapter like this:
try
{
conn.Open();
using(SqlDataAdapter da = new SqlDataAdapter(cm))
{
da.Fill(DataTable dt);
}
}
I'm developing a C# solution with data access to Oracle.
And would like to have a generic solution about query.
Here is a part of my code :
public DataTable GetData(string query)
{
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
using (DbConnection conn = factory.CreateConnection())
{
try
{
DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder();
csb["Data Source"] = #"Northwind";
csb["User Id"] = #"Northwind";
csb["Password"] = #"Northwind";
conn.ConnectionString = csb.ConnectionString;
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
using (DataTable dt = new DataTable())
{
DbDataAdapter da = factory.CreateDataAdapter();
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
catch (Exception ex)
{
throw new Exception("Error", ex);
}
finally
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}
}
}
And I call my method like this :
DataAccess.Provider data = new DataAccess.Provider();
DataTabel dt = dt.GetData("select * from myTable);
This works pretty good but this is not my aim.
I have a second class called CL_mpg with all my SQL queries.
class CL_MPG
{
public string rq_sql;
public string selectParam(string param)
{
this.rq_sql = "select * from myTable where id = '" + param + "';";
return this.rq_sql;
}
public string select()
{
this.rq_sql = "select * from myTable";
return this.rq_sql;
}
//...
}
And I would like to use my methods selectParam and/or select to fill my datatable, but I don't know how to do that.
Although others complain at your learning attempt, everyone has to start somewhere. Your method is actually an ok start, but I would change the parameter from a string to a DbCommand object. Then, you can create your methods to properly build the command and set proper parameters. Then pass the entire prepared command to your wrapper method (that creates connection, tests open successful, queries data, etc) and have your method return a DataTable object as you have... something like
public class CL_MPG
{
private DataTable GetData(DbCommand cmd )
{
// do all the same as you have with exception of your USING DBCOMMAND.
// just set the connection property of the incoming command to that of
// your connection created
// AT THIS PART --
// using (DbCommand cmd = conn.CreateCommand())
// {
// cmd.CommandText = query;
// just change to below and remove the closing curly bracket for using dbcommand
cmd.Connection = conn;
}
// Now, your generic methods that you want to expose for querying
// something like
public DataTable GetAllData()
{
DbCommand cmd = new DbCommand( "select * from YourTable" );
return GetData( cmd );
}
public DataTable GetUser( int someIDParameter )
{
DbCommand cmd = new DbCommand( "select * from YourTable where ID = #parmID" );
cmd.Parameters.Add( "#parmID", someIDParameter );
return GetData( cmd );
}
public DataTable FindByLastName( string someIDParameter )
{
DbCommand cmd = new DbCommand( "select * from YourTable where LastName like #parmTest" );
cmd.Parameters.Add( "#parmTest", someIDParameter );
return GetData( cmd );
}
}
Notice the command is being built and fully prepared and parameterized vs concatination of strings as prior comment was made which could expose you to SQL-injection. As for the parameters, and not querying Oracle, they may need to be tweaked some. Different engines use slightly different conventions. If connecting to SQL-Server database, it uses "#" to identify a parameter. In SyBase Advantage Database, it uses ":". Using Visual FoxPro, a simple "?" placeholder is used.
Also, if your query has many criteria, just keep adding additional "#parm" type placeholders, then add your parameters in the same order as they appear in your query just to make sure you didn't miss any. Some functions could have none, one or more based on your needs. Then, in the samples provided, its as simple as doing something like
DataTable whoIs = yourCL_MPGObject.GetUser( 23 );
if( whoIs.Rows.Count > 0 )
MessageBox.Show( whoIs.Rows[0]["WhateverColumnName"] );
How can i read the return value from "Select Where" statement , every time i run no return value appear in the label, and no syntax error.
command.CommandText = "select product_price from product where product_name='"+x+"';";
connection.Open();
Reader = command.ExecuteReader();
while(Reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
connection.Close();
If the product_price column is not of type TEXT in MySQL, the Reader.GetString(0) will (depending on how the reader was implemented by Oracle) throw an Exception or return an empty string. I would think the latter is happening.
Retrieving the value through a DataReader requires you to know the data type. You can not simply read a string for every type of field. For example, if the field in the database is an Integer, you need to use GetInt32(...). If it is a DateTime use GetDateTime(...). Using GetString on a DateTime field won't work.
EDIT
This is how I'd write this query:
using (MySqlConnection connection = new MySqlConnection(...))
{
connection.Open();
using (MySqlCommand cmd = new MySqlCommand("select product_price from product where product_name='#pname';", connection))
{
cmd.Parameters.AddWithValue("#pname", x);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
sb.Append(reader.GetInt32(0).ToString());
Price_label.Content = sb.ToString();
}
}
}
To append to my comment, your approach has three problems which are not part of your problem:
SQL-Injection, always use parameterized queries.
Leaking resources, IDisposable-Objects need to be treated properly.
Bad habits, "" + string for casting is...uhhh...not good and not necessary.
So, a more correct version for your code would look like this:
// using utilizes the IDisposable-Interface, whcih exists to limit the lifetime
// of certain objects, especially those which use native resources which
// otherwise might be floating around.
using(YourConnectionType connection = new YourConnectionType("connectionstring"))
{
connection.Open(); // You might want to have this in a try{}catch()-block.
using(YourCommandType command = connection.CreateCommand())
{
command.CommandText = "select product_price from product where product_name=#NAME;";
command.Parameters.Add("NAME", YourTypes.VarChar);
command.Parameters[0].Value = x; // For your own sanity sake, rename that variable!
using(YourReaderType reader = command.ExecuteReader())
{
while(reader.Read()) // If you're expecting only one line, change this to if(reader.Read()).
{
Price_label.Content = reader.GetString(0);
}
}
}
} // No need to close the conenction explicit, at this point connection.Dispose()
// will be called, which is the same as connection.Close().
you have to create a variable of your reader
command.CommandText = "select product_price from product where product_name='"+x+"';";
try {
connection.Open();
SqlReader reader = command.ExecuteReader();
while(reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
} catch (Exception) {}
finally {
connection.Close();
}
You should write #pname without '' otherwise it won't work.
instead of:
select product_price from product where product_name='#pname'
you should write like this:
select product_price from product where product_name=#pname