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 + "%'");
Related
I'm trying to create an api endpoint that returns an element by id , but JsonResult makes an array from DataTable which is supposed to have only one object
[HttpGet("{id:int}")]
public JsonResult GetUser(int id)
{
string query = #"select id,number,name,lastName from dbo.Users where id=" + id;
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("UsersDb");
SqlDataReader myreader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myComm = new SqlCommand(query, myCon))
{
myreader = myComm.ExecuteReader();
table.Load(myreader);
myreader.Close();
myCon.Close();
}
}
return new JsonResult(table);
}
However i get this result with squared brackets on the sides
[{"id":4,"number":10,"name":"Peter","lastName":"Peterson"}]
try this
return new JsonResult(JArray.FromObject(dt).First())
result
{"id":4,"number":10,"name":"Peter","lastName":"Peterson"}
You can just return table.Rows[0] rather than the whole table.
There are other improvements here:
Parameterize your query. Do not inject data into your SQL.
Missing using on the reader.
Consider making this function async
[HttpGet("{id:int}")]
public JsonResult GetUser(int id)
{
const string query = #"#
select
id,
number,
name,
lastName
from dbo.Users
where id = #id;
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("UsersDb");
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
using (SqlCommand myComm = new SqlCommand(query, myCon))
{
myComm.Parameters.Add("#id", SqlDbType.Int).Value = id;
myCon.Open();
using(var myreader = myComm.ExecuteReader())
{
table.Load(myreader);
}
}
return new JsonResult(table.Rows[0]);
}
I created an Android app like social media app. I'm using ASP.NET web services for fetching data with JSON or process data like INSERT, UPDATE, DELETE. And I'm using MySQL database.
Number of active users is about 2,5k and daily average is 1,5k.
Anyway, when I control process list with "show processlist;" on phpMyAdmin , there are a lot of process; some processes has Sleep command value. So this situation gets errors like decreasing app speed and some times "max_user_connections".
So, I closed all connections after completing process of database on Web Service, but still have that issue or errors.
[WebMethod]
public string ABC(int x, string y)
{
using (con = new MySqlConnection(conString))
{
List<Profile> result= new List<Profile>();
result.Add(new Profile
{
posts= ""
});
List<ClassA> resultA= new List<ClassA>();
query= "SELECT COUNT(FollowId) FROM Followings WHERE FUserId = " + x;
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
string count = "0";
while (dr.Read())
{
count = dr[0].ToString();
}
dr.Close();
con.Close();
query= "SELECT COUNT(FollowId) FROM Followings WHERE FollowingUserId = " + x;
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
string count2 = "0";
while (dr.Read())
{
count2 = dr[0].ToString();
}
dr.Close();
con.Close();
query= "SELECT .... FROM Posts WHERE UserId = " + x+ " ORDER BY PostId DESC LIMIT 30";
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
int i;
int count3 = 0;
while (dr.Read())
{
count3++;
i = 0;
resultA.Add(new ClassA
{
postId = Convert.ToInt32(dr[i]),
postUrl = dr[++i].ToString(),
... = Convert.ToInt32(dr[++i])
});
}
dr.Close();
con.Close();
string json = "";
if (resultA.Count > 0)
{
json = JsonConvert.SerializeObject(resultA);
}
result[0].posts = json;
json = "";
if (result.Count > 0)
{
json = JsonConvert.SerializeObject(result);
}
return json;
}
}
It's any example of my web methods. Where do I mistake ?
Thanks for replies.
I want to remove backslash from json result
current result like this:
"{\"Info\":[{\"Full_Eng_Nmae\":\"anda norse\",\"email\":\"keer0#gm
my code is like this
public string GetDetails(string OrderID)
{
OrderContract order = new OrderContract();
DataSet dataSet = new DataSet();
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
con.Close();
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select Full_Eng_Nmae,email,mobile,client_id from Students where Center_id='" + OrderID + "'", con);
da.Fill(dataSet,"Info");
dataSet.AcceptChanges();
string json = JsonConvert.SerializeObject(dataSet);
return json;
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
any one can help me plz?
Thanks
also this full of my code
my Interface:
[ServiceContract]
public interface IOrderService
{
[OperationContract]
[WebGet(UriTemplate = "/GetOrderDetails/{OrderID}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string GetOrderDetails(string OrderID);
}
I bet there is no backslash, but the printing code that you are using is adding them.
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));
Currently, I am creating an application using ASP.NET MVC3 and MySQL and when I try to retrieve a user's first name from the databse I receive a System.FormatException: Input string was not in a correct format.
This is my code:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
object result = cmd.ExecuteScalar();
if (result != null)
{
string fname = Convert.ToString(result);
return fname;
}
else
{
string fname = "friend";
return fname;
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
This is MySQL Stored Procedure:
CREATE DEFINER=`0001`#`%` PROCEDURE `SP_GET_FNAME`(IN id BIGINT(20), OUT first_name VARCHAR(60))
BEGIN
DECLARE user_id BIGINT(20) DEFAULT id;
DECLARE output VARCHAR(60);
SELECT `FName` FROM `users` WHERE USERID=user_id INTO output;
SET first_name = output;
END
The problem seems to be when executing cmd.ExecuteScalar().
What is my problem here?
Thank you in advance!
Copy and paste error on my part. The correct code that works as expected is:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
cmd.ExecuteScalar();
string fname = Convert.ToString((cmd.Parameters["first_name"].Value));
return fname;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
CORRECTION: cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
NOT: cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
In my case, the FNAME field in the user table cannot be NULL; therefore, checking for NULL values returned in the code is not necessary.
I would guess that the user is not found or the fname is null.
And I really hope you're not querying the database for each user column.
Good luck.
An additional comment.
When trying to return a string value the AddWithValue appears to be trying to convert the output from a string into a number. This results in the string format exception.