how to query select data from table where first 3 character defined - c#

i want to filter dropdownlist by first 3 charater on job code, this is my query
string result3 = Checked_By.ToString().Substring(0, 3);
SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama]
FROM [Job] WHERE LEFT(Kode, = '" + result3 + "') ORDER BY
Nama ASC", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
sda.Fill(dt);
con.Close();

This is straightforward fix. First, fix SQL syntax error (SQL LEFT function takes 2 parameter, a string and a number. LEFT('abcdef', 3) returns abc), next rewrite using parameters. Something like this.
string result3 = Checked_By.ToString().Substring(0, 3);
SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama] FROM [Job] WHERE LEFT(Kode, 3) = #result3 ORDER BY Nama", con); //ASC is OK but not required as it is default option
cmd.Parameters.Add("#result3", SqlDbType.Char, 3).Value = result3;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
//con.Open(); //not necessary. SqlDataAdapter.Fill opens connection if it needs
sda.Fill(dt);
//con.Close(); //and closed if it wasn't open before .Fill

"SELECT [Kode], [Nama]
FROM [Job] WHERE SUBSTR(Kode,1,3) = '" + result3 + "' ORDER BY
Nama ASC"

Related

c# asp.net check if column in database contains string

In my database, the column is stored as 'Here is jurong', I want to read out the database row if the column contains the word jurong.
I tried using like but it cant work
Here is the code, please help
cmd = new SqlCommand("Select * from Thread WHERE (Delete_Status='No') AND (Thread_Location = '" + searchTB.Text + "' OR Thread_Title = '" + searchTB.Text + "' OR Thread_Description LIKE '%' + #Thread_Description + '%') ORDER BY ThreadID DESC ", con);
cmd.Parameters.Add("#Thread_Description", SqlDbType.VarChar).Value = searchTB.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
reptater.DataSource = ds;
reptater.DataBind();
Does that SQL statement return rows when you run it in the database? Also, I'd be careful of SQL injection attacks when passing values not through parameters.
Should your 'reptater' bind to a DataTable rather than a DataSet?
cmd = new SqlCommand("SELECT * FROM Thread WHERE (Delete_Status='No') AND (Thread_Location = #SearchTxt OR Thread_Title = #SearchTxt OR Thread_Description LIKE '%' + #SearchTxt + '%') ORDER BY ThreadID DESC ", con);
cmd.Parameters.Add("#SearchTxt", SqlDbType.VarChar);
cmd.Parameters["#SearchTxt"].Value = searchTB.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
reptater.DataSource = ds; //ds.Tables[0]; ?
reptater.DataBind();

Database update error with SQL Server 2012 and C#

I am trying to update my data in a SQL Server database through C#. I am getting updated. But the problem is the data is updated twice.
For example I have 10 (int) in my balance and if I add another 10, it turns to 30.
Any help would be appreciated.
Here is my code:
protected void LoginClick(object sender, EventArgs e)
{
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
}
I would like to rectify few mistakes in your code,
DataTable is not needed to execute the update query, ExecuteNonQuery will do the job
The adapter.Fill and ExecuteNonQuery do the same job here and that's why your updates happening twice
Make use of parameterization while dealing with user inputs to avoid exceptions
For parsing integers use int.TryParse instead for Convert.ToInt32
I think the following code would help you to do the same function in a smarter way:
int currentBalance = 0;
if(int.TryParse(txtAdd.Text, out currentBalance))
{
string querSql = "Update [Order] set Balance = Balance + #balance," +
" Card = #card where email = #email"
using (SqlConnection dbConn = new SqlConnection("connectionString here"))
{
dbConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(querySql, dbConn))
{
sqlCommand.Parameters.Add("#balance", SqlDbType.int).value = currentBalance;
sqlCommand.Parameters.Add("#card", SqlDbType.VarChar).value = card.Text;
sqlCommand.Parameters.Add("#email", SqlDbType.VarChar).value = email;
sqlCommand.ExecuteNonQuery();
}
}
}
Please note: YOu are parsing the balance as an integer value, so I assume the column Balance is an integer field in the database, if not make use of corresponding datatype for the parameter #balance also update the parsing technique
As per the documentation:
SqlDataAdapter(SqlCommand)
Initializes a new instance of the SqlDataAdapter class with the specified SqlCommand as the SelectCommand property.
What is going wrong in your code?
Actually you are passing SqlDataAdapter your update query as the Select command. So now when you will use this instance of SqlDataAdapter to Fill your datatable then actually you are executing your Update command. Look at the following code along with comments to see what is going wrong:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);//The Select command for SqlDataAdapter
//is actually now the update command specified by cmd instnace of SqlCommand
DataTable dt = new DataTable();
sda.Fill(dt);//here SqlDataAdapter will execute it's Select command which is actually set
//to an update statement so your record will be updated
int i = cmd.ExecuteNonQuery();//and here again the update command is being executed now
//directly using the SqlCommand cmd instance and thus your record gets updated twice
con.Close();
Fixed Code:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
//Create a new SqlComamnd
SqlCommand selectCommand = new SqlCommand("Select * from [Order]");
//Put the newly created instance as SelectCommand for your SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
Hope this help and do have a look at the documentation for better understanding of the SqlDataAdapter and DataTable. Thanks.

how to display date and time separately in grid view

I have one column in SQL table. which name is Intime. Its data type is nvarchar. It stores both date and time. But I want date and time separately.
I have tried this query:
select AttendanceDate,
SUBSTRING(convert(varchar,intime,113),1,11)[Intime],
SUBSTRING(convert(varchar,intime,113),13,19)[InTime],
InDeviceId,
OutTime,
OutTime,
OutDeviceId,
dbo.MinutesToDuration(duration) as Duration,
Status
from dbo.AttendanceLogs
where EmployeeId=2938
order by AttendanceDate desc
but if I pass same SQL command in grid view its not working.
public void Bind()
{
SqlCommand cmd = new SqlCommand("select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTime],SUBSTRING(convert(varchar,InTime,113),13,19) as [Intime],InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem + " and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter();
cmd.Connection = con;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
Where possibly could be the problem?
replace your code with this
public void Bind()
{
SqlCommand cmd = new SqlCommand(#"select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTimeD],SUBSTRING(convert(varchar,InTime,113),13,19) as [IntimeT],
InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs
where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem.Value +
" and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd,con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
this line not filter any year it return object of drop down list
year(AttendanceDate)=" + ddlYear.SelectedItem + "

Dropdownbox.selectedvalue passing to sql comment

string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "Select * from table1 order by("+ddorder+" "+ddtype+")";
//there is an error beacuse of ddtype, what am I doing wrong?
SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1, DropDownList2.SelectedValue);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();
As far as I can see, you don't need to use ( and ) in order by clause. It's syntax doesn't have any usage for ( or ).
For example;
order by id desc
will work but
order by (id desc)
won't work.
By the way, use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter automatically instead of calling Close method manually.
Also you don't need cmd.ExecuteNonQuery(); part for a SELECT statement. It is unnecessary since it's just execute your select query. It doesn't do or return something.
A few things more;
Change your table1 to something meaningful.
Don't use SELECT *. It's quite bad.
Use Dynamic Query:
Change Here:
string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "exec(Select * from table1 order by "+ddorder+" "+ddtype+")";
and
SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();
Remove the parenthesis in the "order by" clause:
String str1 = "Select * from table1 order by "+ddorder+" "+ddtype;

Connecting two tables into one datagridview using RIGHT JOINT

I have got this code below, which should connect 2 tables (ZAJSLUZ and KLISLUZ) but I need to add into it condition to select only those from ZAJSLUZ where column AKCE = zakce.Text
Would someone improve my code please ?
It gives me error that there is "bad syntax near ="
DataTable dt = new DataTable();
//SqlDataAdapter SDA = new SqlDataAdapter("select * from zajsluz",spojeni);
SqlDataAdapter SDA = new SqlDataAdapter("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.akce="+zakce.Text, spojeni);
SDA.Fill(dt);
dtg_ksluzby.DataSource = dt;
check if zakce.Text is a valid string before.
string sZakce = string.Empty;
if(zakce != null && zakce.Text != null)
{
sZakce = zakce.Text;
}
string sQuery = string.Format("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.akce= '{0}'", sZakce)
SqlDataAdapter SDA = new SqlDataAdapter(sQuery, spojeni);
i also suggest you to use the using block if you work with DataAdapters, so your adapter is disposed automatically.
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM table", con))
{
// use your adapter a
}
Change your line like this.
SqlDataAdapter SDA = new SqlDataAdapter("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.akce='"+zakce.Text+"'", spojeni);
...zajsluz.akce=+"zakce.Text,...
you might want to change it into
...zajsluz.akce='"+zakce.Text+"'",...
Change your line to
SqlDataAdapter SDA = new SqlDataAdapter("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.aakce='" + zakce.Text + "'", spojeni);
SqlDataAdapter SDA = new SqlDataAdapter("SELECT zajsluz.akce ,zajsluz.text,klisluz.pocet FROM zajsluz RIGHT JOIN klisluz ON zajsluz.ID=klisluz.id WHERE zajsluz.akce= '" +zakce.Text +"'", spojeni);

Categories