I currently have a query string for the jQuery Autocomplete plug in but should be using a stored procedure instead. Can anyone help me convert? It seems to not be working when I do it.
Original ASHX
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["Rollup2ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
//cmd.CommandText = "select NUID from T_USER where " +
//"NUID like #SearchText + '%'";
cmd.CommandText = "select rtrim(NUID) NUID, rtrim(FNAME) FNAME, rtrim(LNAME) LNAME from T_USER where NUID like #SearchText + '%' OR FNAME like #SearchText + '%' OR LNAME like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["NUID"].ToString() + " ").Append(sdr["FNAME"].ToString() + " ").Append(sdr["LNAME"].ToString() + " ")
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
New ASHX for stored procedure:
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["Rollup2ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
//cmd.CommandText = "select NUID from T_USER where " +
//"NUID like #SearchText + '%'";
cmd.CommandText = "SP_AUTOCOMPLETE";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Parameters.Add(new SqlParameter("#SearchText", SqlDbType.VarChar));
cmd.Parameters["#SearchText"].Value = prefixText;
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["NUID"].ToString() + " ").Append(sdr["FNAME"].ToString() + " ").Append(sdr["LNAME"].ToString() + " ")
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
Stored procedure:
#SearchText VARCHAR(255)
AS
BEGIN
SET NOCOUNT ON;
SELECT RTRIM(NUID) NUID, RTRIM(FNAME) FNAME, RTRIM(LNAME) LNAME
FROM T_USER
WHERE NUID like #SearchText + '%' OR FNAME like #SearchText + '%' OR LNAME like #SearchText + '%'
Thanks!
You need to set the SqlCommand 'CommandType' to 'CommandType.StoredProcedure'.
cmd.CommandType = CommandType.StoredProcedure;
I would also recommend using a prefix other than 'sp_'. That is what Microsoft used for their system procedures and you might accidentally overwrite one you want to keep around. :)
This is how I generate parameters:
public static SqlParameter GetParameter(string parameterName, object value, SqlDbType type, int size)
{
if (value == null)
{
value = DBNull.Value;
}
if (size <= 0 && type == SqlDbType.VarChar)
{
switch (type)
{
case SqlDbType.VarChar:
size = 8000;
break;
case SqlDbType.NVarChar:
size = 4000;
break;
}
}
SqlParameter parameter = new SqlParameter(parameterName, type, size);
parameter.Value = value;
parameter.IsNullable = true;
return parameter;
}
And I just do this.
cmd.Parameters.Add(GetParameter("#SearchText", searchText, SqlDbType.VarChar));
Related
I want get image from API to XAMARIN I have API connected to MYSQL if I try get image he give me nothing that is the code.
API
[HttpGet]
public string Plan(string Code, string Company, string Centrale, string Zone)
{
object imag = null;
DataSet ds = new DataSet();
try
{
MySqlConnection con = new MySqlConnection(connectionDB.ConnectionString);
MySqlCommand cmd = new MySqlCommand("select imag from photo inner join taskhis on photo.company = taskhis.company and " +
" photo.zone = taskhis.zone where taskhis.codes ='" + Code + "' and taskhis.company ='" + Company + "' " +
"and taskhis.centrale = '" + Centrale + "' and taskhis.zone = '" + Zone + "' and dates ='" + DateTime.Now.ToString("yyyy/MM/dd") + "' group by taskhis.zone", con);
con.Open();
MySqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
imag = dr[0];
}
//MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//da.Fill(ds);
dr.Close();
con.Close();
}
catch (Exception ex)
{
}
return imag.ToString() ;
}
connection method
string MainUri = "http://192.168.1.25:5873/api/C1NET/";
public async Task<string> GetRequest(string uri)
{
string Tache = "";
var client = new RestClient(MainUri);
var request = new RestRequest(uri);
var response = client.Execute(request);
return response.Content;
}
MainPage
string[] item = plan.urTask.Split(';');
VPNConnector VP = new VPNConnector();
string Result = VP.GetRequest("Plan?Code=" + item[4]+ "&Company="+item[0]+ "&Centrale="+item[1]+ "&Zone="+item[2]).Result;
byte[] image = Encoding.ASCII.GetBytes(Result);
MemoryStream ms = new MemoryStream(image);
IMAGES.Source = ImageSource.FromStream(() => ms);
please if someone can help me to fix my code that can be great thank you
I am developing a search functionality in restful web service,from code i am passing searching string parameter to a method.i am getting the matched string response from database,Now how to validate whether input search string is exist or not from database.
public MemberEntity Search(string prefix)
{
try
{
MemberEntity ObjMember = new MemberEntity();
string sql = string.Format(#"select first_name, last_name from member_master where first_name like ('#prefix')");
using (MySqlConnection conn = new MySqlConnection(UtilityHelper.getConn()))
{
//using (MySqlCommand cmd = new MySqlCommand(string.Format("select first_name, last_name from member_master where first_name like ('#prefix%')"), conn))
using (MySqlCommand cmd = new MySqlCommand(sql.ToString(), conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#prefix", prefix);
cmd.CommandType = CommandType.Text;
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
ObjMember.Name = string.Format("{0} {1}", dr["first_name"].ToString(), dr["last_name"].ToString());
}
}
}
}
return ObjMember;
}
catch (Exception ex)
{
throw ex;
}
#endregion
}
Your sql should be like this.
string sql = string.Format(#"select first_name, last_name from member_master where first_name like '" + #prefix + "%'");
I have two functions that have queries that return shipping areas. One returns a pilots certified areas and the other returns areas between point A and B. I want to compare them and select the check boxes of the matching areas. Here is what I have.
private void getAreaText(string PilotID)
{
SqlConnection sqlCN;
SqlCommand sqlCOM;
SqlDataReader sqlDR;
DateTime dato;
string strCOM = ConfigurationManager.AppSettings["database"];
sqlCN = new SqlConnection(strCOM);
try
{
sqlCN.Open();
sqlCOM = new SqlCommand("select f_AreaText, f_DateOfIssue from v_GetAreaText where f_PilotID='" + PilotID + "'", sqlCN);
sqlDR = sqlCOM.ExecuteReader();
CheckBoxList1.Items.Clear();
while (sqlDR.Read())
{
dato = sqlDR.GetDateTime(1);
dato = dato.AddYears(1);
if (DateTime.Now < dato)
CheckBoxList1.Items.Add(sqlDR.GetString(0));
if (CheckBoxList1.Items.Contains(findAreas(Session["PilotID"].ToString)))
{
CheckBoxList1.Items[i].Selected = true;
}
}
sqlDR.Close();
}
catch (DataException ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlCN.Close();
sqlDR = null;
sqlCOM = null;
sqlCN = null;
}
return;
}
protected void findAreas(string PilotID)
{
SqlConnection sqlCN;
SqlCommand sqlCOM;
SqlDataReader sqlDR;
string strCOM = ConfigurationManager.AppSettings["database"];
sqlCN = new SqlConnection(strCOM);
try
{
sqlCN.Open();
sqlCOM = new SqlCommand("select DISTINCT f_AreaText from v_FindAreas where f_PilotID='" + PilotID + "'and f_SailedFrom='" + getLMFromList(FromList) + "'and f_SailedTo='" + getLMFromList(ToList) + "'", sqlCN);
sqlDR = sqlCOM.ExecuteReader();
CheckBoxList1.Items.Clear();
while (sqlDR.Read())
{
CheckBoxList1.Items.Add(sqlDR.GetString(0));
}
sqlDR.Close();
}
catch (DataException ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlCN.Close();
sqlDR = null;
sqlCOM = null;
sqlCN = null;
}
return;
}
Your code is quite confusing so here is an attempt to organize it a little and make it work at the same time. There's a lot more you could do to improve it but since I'm coding in the dark, I haven't changed it too much. The main thing I've changed is to use SQL parameters instead of concatenating values into a literal command.
private void getAreaText(string PilotID)
{
var strCOM = ConfigurationManager.AppSettings["database"];
var sqlCN = new SqlConnection(strCOM);
try
{
sqlCN.Open();
var sqlCOM = new SqlCommand("select f_AreaText, f_DateOfIssue from v_GetAreaText where f_PilotID=#p1", sqlCN);
sqlCOM.Parameters.AddWithValue("#p1", PilotID);
var sqlDR = sqlCOM.ExecuteReader();
CheckBoxList1.Items.Clear();
while (sqlDR.Read())
{
var dato = sqlDR.GetDateTime(1);
dato = dato.AddYears(1);
if (DateTime.Now < dato)
{
var AreaText = sqlDR.GetString(0);
CheckBoxList1.Items.Add(AreaText);
if (findAreas(PilotID, AreaText))
// Do you want Selected here or Checked ?
CheckBoxList1.Items[CheckBoxList1.Count-1].Selected = true;
}
}
}
catch (DataException ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlDR.Close();
sqlCN.Close();
sqlDR = null;
sqlCOM = null;
sqlCN = null;
}
return;
}
protected bool findAreas(string PilotID, string AreaText)
{
var strCOM = ConfigurationManager.AppSettings["database"];
var sqlCN = new SqlConnection(strCOM);
try
{
sqlCN.Open();
sqlCOM = new SqlCommand("select DISTINCT f_AreaText from v_FindAreas where f_PilotID=#p1 and f_SailedFrom=#p2 and f_SailedTo=#p3 and f_AreaText=#p4", sqlCN);
sqlCOM.Parameters.AddWithValue("#p1", PilotID);
sqlCOM.Parameters.AddWithValue("#p2", getLMFromList(FromList));
sqlCOM.Parameters.AddWithValue("#p3", getLMFromList(ToList));
sqlCOM.Parameters.AddWithValue("#p4", AreaText);
var sqlDR = sqlCOM.ExecuteReader();
if (sqlDR.HasRows)
return true;
}
catch (DataException ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlDR.Close();
sqlCN.Close();
sqlDR = null;
sqlCOM = null;
sqlCN = null;
}
return false;
}
Hi i was using stored procedure in SQL Server to pass parameters to the query ,
but now I'm changing my database to ms access and it's my first time to deal with.
how can i pass byte[] to sql query ?
bacause i got this error
Syntax error (missing operator) in query expression 'System.Byte[]'.
this is my code
public static int EditWhois(object ID,object Image, object Ranswer, object Fanswer1, object Fanswer2, object Fanswer3)
{
int result = 0;
String sql = "UPDATE Whois SET [Image]="+#Image+", Ranswer=" + Ranswer + ", Fanswer1=" + Fanswer1 + ",Fanswer2=" + Fanswer2 + ",Fanswer3=" + Fanswer3 + " WHERE ID=" + ID;
System.Windows.Forms.MessageBox.Show(sql);
cmd = new OleDbCommand(sql, con);
//cmd.Parameters.AddWithValue("#ID", ID);
//cmd.Parameters.AddWithValue("#Image", Image);
//cmd.Parameters.AddWithValue("#Ranswer", Ranswer);
//cmd.Parameters.AddWithValue("#Fanswer1", Fanswer1);
//cmd.Parameters.AddWithValue("#Fanswer2", Fanswer2);
//cmd.Parameters.AddWithValue("#Fanswer3", Fanswer3);
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
return result;
}
Use # parameter substitution. Also as #BoltClock says, change you method signature.
public static int EditWhois(object ID,object Image, object Ranswer,
object Fanswer1, object Fanswer2, object Fanswer3)
{
int result = 0;
String sql = "UPDATE Whois SET [Image]=#Image, Ranswer=#Ranswer, " +
"Fanswer1=#Fanswer1, Fanswer2=#Fanswer2, Fanswer3=#Fanswer3 " +
"WHERE ID=#ID";
cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Image", Image);
cmd.Parameters.AddWithValue("#Ranswer", Ranswer);
cmd.Parameters.AddWithValue("#Fanswer1", Fanswer1);
cmd.Parameters.AddWithValue("#Fanswer2", Fanswer2);
cmd.Parameters.AddWithValue("#Fanswer3", Fanswer3);
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
return result;
}
result is still 0;
i know the problem where it was .
if the connection is closed the query will be executed successfully , but if it is opend it will not be executed due to this condition .
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
it must be
if (con.State != ConnectionState.Open)
{
con.Open();
}
result = cmd.ExecuteNonQuery();
con.Close();
thanks all .
How to connect infobright DB through perl ?
With DBD-mysql. Install it with
perl Makefile.PL --mysql_config=/usr/local/infobright-3.5.2-x86_64/bin/mysql_config
or similar.
You can connect to Infobright using any standard database connection that you'd use with MySQL. Daxim is correct -- DBD is one of the most common ways to connect to the database. In your DBD config, all you'd need to do is change the port number from 3306 (MysQL) to 5029 (Infobright). All the rest is the same.
**INSERT **
if (textBox4.Text == "")
{
MessageBox.Show("Please provide Selling1 ", "Item Update", MessageBoxButtons.OK);
textBox4.Focus();
return;
}
int i = dbcon.writer("insert into Item_Master(Item_Code,Name,Description,Selling1,Selling2,Reorder_level,Reorder_Quantity,Active) Values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')");
if (i == 1)
{
MessageBox.Show("Record added succesfully", "Item Table");
Itemview();//disply ll
iclear();
}
else
{ MessageBox.Show("Record unsuccesfully for Item "); }
}
**INSERT **
Dbcontrol dbcon = new Dbcontrol();
SqlDataReader dr = null;
string date = DateTime.Now.ToString("M/d/yyyy");
VIEW/SEARCH
listView1.Items.Clear();
dr = dbcon.reader("select cateid,brand,type,deta,date from emcategory where cateid like '%" + txtseacrchid.Text + "%'");
while (dr.Read())
{
string sid = dr["cateid"].ToString();
string id = dr["brand"].ToString();
string pname = dr["type"].ToString();
string dis = dr["deta"].ToString();
string tim = dr["date"].ToString();
string[] row = { sid, id, pname, dis, tim };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
}
VIEW/SEARCH*
**UPDATE **
try
{
DialogResult x = MessageBox.Show("Do You Really Want To Update This Record", "Cash Book Details", MessageBoxButtons.YesNo);
if (x == DialogResult.Yes)
{
upate.Enabled = true;
delete.Enabled = false;
foreach (ListViewItem item in listView1.SelectedItems)
{
txtid.Text = item.SubItems[0].Text;
txtBrand.Text = item.SubItems[1].Text;
txttyp.Text = item.SubItems[2].Text;
txtdec.Text = item.SubItems[3].Text;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
**UPDATE **
DELETE
DialogResult x = MessageBox.Show("Do You Really Want To Delete This Record", "Item Category", MessageBoxButtons.YesNo);
if (x == DialogResult.Yes)
{
delete.Enabled = true;
int i = dbcon.writer("delete from Ritemcategory where cateid='" + txtid.Text + "'");
if (i == 2 || i == 1)
{
MessageBox.Show("Deleted Succesfully", "Item Category");
view();
generatePid();
}
}
else
{
delete.Enabled = false;
}
DELETE
STOREDPROCEDURE
public void generatePid()
{
dr = dbcon.reader("Genarate_itemcategory_id");
while (dr.Read())
{
txtid.Text = dr["value"].ToString();
}
}
//////////////////KEYDOWN////////////
//////////////////
//////////////////KEYPRESS////////////
//////////////////
//////////////////SELECTEDVALUE////////////
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
upate.Enabled = false;
Save.Enabled = false;
delete.Enabled = true;
foreach (ListViewItem item in listView1.SelectedItems)
{
txtid.Text = item.SubItems[0].Text;
txtBrand.Text = item.SubItems[1].Text;
txttyp.Text = item.SubItems[2].Text;
txtdec.Text = item.SubItems[3].Text;
}
}
//////////////////
//////////////////KEYDOWN////////////
if (e.KeyCode == Keys.Enter)
{
insert();
}
//////////////////
public void log()
{
dr = dbcon.reader("select * from Admin where id = ' 1'");
while (dr.Read())
{
string un = dr["fuser"].ToString();
string ped = dr["fpassword"].ToString();
if ((textBox1.Text == "" || textBox1.Text == null) || (textBox2.Text == "" || textBox2.Text == null))
{
MessageBox.Show("Please enter username and password");
}
else
{
if (textBox1.Text == un && textBox2.Text == ped)
{
logdetail();
}
else
{
MessageBox.Show("User Name or Password is incorrect");
}
}
}
}
//////////////////KEYDOWN////////////
//////////////////
class Dataconnection
{
public static SqlConnection NewCon;
//public static string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public static SqlConnection GetConnection()
{
NewCon = new SqlConnection("Data Source=Absar;Initial Catalog=star_fancy_stock;Integrated Security=True;");
return NewCon;
}
}
///////////////////////
2ND
//////////////////
namespace star_fancy_stock
{
class Dbcontrol
{
public static SqlConnection NewCon;
SqlDataReader dr;
public int dataread = 0;
public Dbcontrol()
{ }
public SqlDataReader reader(String sql)
{
try {
NewCon = Dataconnection.GetConnection();
NewCon.Open();
SqlCommand newconn = new SqlCommand(sql, NewCon);
dr = newconn.ExecuteReader();
return dr;
}
catch (Exception ex) { MessageBox.Show(ex.Message); return dr; }
}
public int writer(String sql)
{
try
{
dataread = 0;
NewCon = Dataconnection.GetConnection();
NewCon.Open();
SqlCommand newconn = new SqlCommand(sql, NewCon);
dataread = newconn.ExecuteNonQuery();
NewCon.Close();
return dataread;
}
catch (Exception ex) { MessageBox.Show(ex.Message); return dataread; }
}
}
}