I am using SQL Server database and there's a column named Cell(VARCHAR) data type. While reading using reader.Read() I get the Conversion error. Can anyone kindly explain the reason for the error?
This is my code:
string myConnection = dbController.connectionString;
string query1 = "SELECT ID, Name from Manager Where Cell = " + managerNo.Text;
using (var conn = new SqlConnection(myConnection))
using (var cmd = new SqlCommand(query1, conn))
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
managerID = reader.GetString(0);
mgrID.Text = managerID;
managerNames.Text = reader.GetString(1);
}
conn.Close();
}
I am reading the value from a textbox (managerNo). I have tested the query on SQL Server Management Studio as well:
select Name, DOB
from Contact
where Cell = 1233453411
When I use Cell = 1233453411 without the value as string I get the conversion error, however using Cell = '1233453411' as a string the result is fetched.
Whats the reason for this and how to solve this issue.
Thanks.
This is a comparison between two different types, a string and an integer:
where Cell = 1233453411
SQL Server has to decide which type to use. It decides on the more restrictive type, which is the number. So, the string gets converted to a number.
Say, you have a cell phone in New York with a number like: 917-555-5555. Well, that becomes a number like 9,175,555,555 and this exceeds the value of the maximum integer. Hence, you would get a conversion overflow.
The moral: Always use similar types when making comparisons.
EDIT:
What should you do? Don't store telephone numbers as numbers; they should be stored as strings (for instance, leading zeroes can be important).
If could do a quick-and-dirty and put single quotes around the value of the parameter. But, what you should really do is change your SQL code to use a parameter with a string type. It is bad programming to just stuff values (particularly user input) into a query string.
Your code is working fine in SQL Server 2008 R2. (Below is tested code)
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\\SQL2008R2;Database=Practice;User ID=sa;Password=123;Trusted_Connection=True;Connection Timeout=0";
string query1 = "SELECT * from tblTest Where Cell = " + textBox1.Text;
using (var conn = new SqlConnection(str))
using (var cmd = new SqlCommand(query1, conn))
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string aa = reader.GetString(0);
}
conn.Close();
}
Otherwise using can change you query like in below format.
string query1 = "SELECT * from tblTest Where Cell = '" + textBox1.Text + "' ";
Thanks
I want to generate an SQL-query string like this one:
INSERT INTO students (id, name) VALUES (?, ?);
How can I avoid possible sql-injections, if some real values are inserted instead of signs ??
string GetQuery() => "INSERT INTO students (id, name) VALUES (7, #name)"
.Replace("#name", "bad value from user");
Is there any function to prepare parameters in C#? Escaping slashes or quotes? Make a note, I don't have any connection with SQL server and don't want to use EntityFramework.
use parametrized SQL Query for detail check this link
and here is the sample code from same link For Entity Framework
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
// Create a query that takes two parameters.
string queryString =
#"SELECT VALUE Contact FROM AdventureWorksEntities.Contacts
AS Contact WHERE Contact.LastName = #ln AND
Contact.FirstName = #fn";
ObjectQuery<Contact> contactQuery =
new ObjectQuery<Contact>(queryString, context);
// Add parameters to the collection.
contactQuery.Parameters.Add(new ObjectParameter("ln", "Adams"));
contactQuery.Parameters.Add(new ObjectParameter("fn", "Frances"));
// Iterate through the collection of Contact items.
foreach (Contact result in contactQuery)
Console.WriteLine("Last Name: {0}; First Name: {1}",
result.LastName, result.FirstName);
}
For ADO.NET use this link
and here is the sample code from the same link
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT ProductID, UnitPrice, ProductName from dbo.products "
+ "WHERE UnitPrice > #pricePoint "
+ "ORDER BY UnitPrice DESC;";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#pricePoint", paramValue);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
I have the following code:
SqlConnection c = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=BookStoreDataBase1;Integrated Security=True;Pooling=False;");
c.Open();
string raf = string.Format("Select Id from Customer WHERE email='{0}'", DropDownList1.SelectedItem.Text);
SqlCommand comm2 = new SqlCommand(raf, c);
SqlDataReader r = comm2.ExecuteReader();
The object r now has the value of the query which is a row contains that the Id where email equals to random value from drop down list.
what I want is to get the exact value of that "Id" and assign it to label. please help me.
First of all your query is open to SQL Injection attack so change it like this:-
string raf = "Select Id from Customer WHERE email= #Email";
SqlCommand comm2 = new SqlCommand(raf, c);
cmoo2.Parameters.Add("#Email",SqlDbType.NVarchar,20).Value =
DropDownList1.SelectedItem.Text;
You are fetching just one value so it can be done use ExecuteScalar like this:-
labelid.Text= cmoo2.ExecuteScalar.ToString();
But If you want to use SqlDataReader object then it will return the value when you call the Read method:-
using(SqlDataReader reader= cmoo2.ExecuteReader())
{
while (reader.Read())
{
labelid.Text= reader["Id"].ToString();
}
}
There are lot of examples already in stack overflow regarding this topic you can refer any of that answers or try this
using(SqlDataReader r= cmd.ExecuteReader())
{
while (r.Read())
{
var myString = r.GetString(0); //The 0 stands for "the 0'th column", so the first column of the result.
labelid.Text=myString;
}
}
i want to check valid data...
i have a table Divisi with sample data like this:
=====================
IdDivisi NamaDivisi
=====================
1 DivisiA
2 DivisiB
3 DivisiC
in my code, i get value :
string data = DivisiA;DivXXX
so, when checked, the alert will appear invalid data.
I want to get a query like this:
select NamaDivisi from Divisi where NamaDivisi IN('DivisiA','DivXXX')
and the result is null or empty or invalid.
because there are values / data 'DivXXX' is not valid on the table Divisi
But this time, when I debug, I get the query result like this:
select NamaDivisi from Divisi where NamaDivisi IN ('DivisiA;DivXXX')
===================================================
This is the full code.
private string CekValidDivisi(string data)
{
DivisiFacade div = new DivisiFacade();
string getDivisi = div.CekValidData(data);
return getDivisi;
}
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + data + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
please help me to resolve the problem in my code. thank you ...
You have multiple problems in your code, but this is not a place to teach you basics, so I'll try to stick to the topic. If you want to have a parameter like that, you have to create it like that first. I guess the data contains string with value DivisiA;DivXXX (and I presume DivXXX is just a generic name meaning you have multiple divisions there). Probably the easiest way would be to do something like this with it
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string paramData = ParseData(data);
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + paramData + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
private string ParseData(string data)
{
return data.Replace(";", "','");
}
Haven't tried it, but hope you get the idea. Either way, please for your own sake, do some research on what is the best way to handle sql connections in c# and also how to prevent SQL injections.
I have inserted values into sql several times but now i am facing problem with the following code
protected void Button1_Click(object sender, EventArgs e)
{
string connstring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
con = new SqlConnection(connstring);
string name = txtName.Text;
string user = txtUser.Text;
string password = txtPwd.Text;
string email = txtEmail.Text;
long phone=Convert.ToInt64(txtPhone.Text);
string address = txtAddr.Text;
string city = txtCity.Text;
string gender = RadioButtonList1.SelectedItem.ToString();
string dob = txtDOB.Text;
string qualification = DropDownList1.SelectedItem.ToString();
string skills = CheckBoxList1.SelectedItem.ToString();
string insertstring = " insert into JobRegisteration values ("+name+","+user+","+password+","+email+","+phone+","+address+","+city+","+gender+","+dob+","+qualification+","+skills+")";
cmd = new SqlCommand(insertstring,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
When I am inserting values into this through asp.net page, its giving following error.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'sbip'.
Invalid column name 'tttt'.
Invalid column name 'ttt'.
The multi-part identifier "tttttt#sss.ss" could not be bound.
Invalid column name 't'.
Invalid column name 'tttt'.
Invalid column name 'Male'.
Invalid column name 'MCA'.
Invalid column name 'C#'.
where tttt, male mca, etc etc are values that are passed from asp page.
thanks!
use parameters like below and also using statements
string connstring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
// change this select statement based on your exact column names
string insertstring = "insert into JobRegisteration ([Name] ,[User] ,[Password] ,[Email] ,[Phone],[Address] ,[City] ,[Gender] ,[Dob] ,[Qualification] ,[Skills]) values (#name ,#user ,#password ,#email ,#phone,#address ,#city ,#gender ,#dob ,#qualification ,#skills)";
using (var con = new SqlConnection(connstring))
using(var cmd = new SqlCommand(insertstring, con))
{
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#user", txtUser.Text);
// give all the parameters..
con.Open();
cmd.ExecuteNonQuery();
}
You need to wrap your inserted values with ' otherwise the database treat them as column names:
string insertstring = " insert into JobRegisteration values ('"+name+"','"+user+"','"+password+"','"+email+"','"+phone+"','"+address+"','"+city+"','"+gender+"','"+dob+"','"+qualification+"','"+skills+"')";
Also, as other suggested you really should rely on Prepared Statements to avoid such problems (among others).
There are many solution to your problem.
1) Try to fit with this format:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
2) as said haim770, surround your values with '
3) use sql parameters way
4) or look at Linq, that's really simplify way to work with database
You need to add single quote ' in your query:
string insertstring = " insert into JobRegisteration values ('"+name+"','"+user+"','"+password+"','"+email+"','"+phone+"','"+address+"','"+city+"','"+gender+"','"+dob+"','"+qualification+"','"+skills+"')";
use using (pun!), bind variables (a.k.a. parameters), format your query, when query seems dubious put what you want explicitly...
protected void Button1_Click(object sender, EventArgs e) {
string name = txtName.Text;
string user = txtUser.Text;
string password = txtPwd.Text;
string email = txtEmail.Text;
long phone = Convert.ToInt64(txtPhone.Text); // <- what about +77(555)123-456-78?
string address = txtAddr.Text;
string city = txtCity.Text;
string gender = RadioButtonList1.SelectedItem.ToString();
string dob = txtDOB.Text;
string qualification = DropDownList1.SelectedItem.ToString();
string skills = CheckBoxList1.SelectedItem.ToString();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString)) {
con.Open();
using(var cmd = con.CreateCommand()) {
cmd.CommandText =
// replace all "field_for_*" for actual fields
#"insert into JobRegisteration(
field_for_name,
field_for_user,
field_for_password,
field_for_email,
field_for_phone,
field_for_address,
field_for_city,
field_for_gender,
field_for_dob,
field_for_qualification,
field_for_skills)
values (
#prm_name,
#prm_user,
#prm_password,
#prm_email,
#prm_phone,
#prm_address,
#prm_city,
#prm_gender,
#prm_dob,
#prm_qualification,
#prm_skills)";
cmd.Parameters.AddWithValue("#prm_name", name);
cmd.Parameters.AddWithValue("#prm_user", user);
cmd.Parameters.AddWithValue("#prm_password", password);
cmd.Parameters.AddWithValue("#prm_email", email);
cmd.Parameters.AddWithValue("#prm_phone", phone);
cmd.Parameters.AddWithValue("#prm_address", address);
cmd.Parameters.AddWithValue("#prm_city", city);
cmd.Parameters.AddWithValue("#prm_gender", gender);
cmd.Parameters.AddWithValue("#prm_dob", dob);
cmd.Parameters.AddWithValue("#prm_qualification", qualification);
cmd.Parameters.AddWithValue("#prm_skills", skills);
cmd.ExecuteNonQuery();
}
}
}