string as name of new class variable - c#

I'm having trouble figuring this out, I want to put the name I send with the method as name of the new class variable I'm trying to make. This is what I have now.
public void GetDier(string naam)
{
string query = "SELECT * FROM [Dieren] WHERE Diersoort = '" + naam + "'";
sqlconn.Open();
SqlCommand cmd = new SqlCommand(query, sqlconn);
SqlDataReader DR = cmd.ExecuteReader();
string diernaam = DR.GetString(1);
int currency = DR.GetInt32(2);
int TPnodig = DR.GetInt32(3);
Dieren naam = new Dieren(diernaam, TPnodig, currency);
}
I want make the string naam, as the new name of the new dier as I'm trying to do in the piece of code above.

Here you have a more secured method to get the data from db:
public Dieren GetDier(string naam)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Dieren naamValue= new Dieren();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString ="SELECT * FROM [Dieren] WHERE Diersoort = #Diersoort";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Diersoort", naam);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
naamValue.naam= oReader["naam"].ToString();
}
myConnection.Close();
}
}
return naamValue;
}

You can't use a variable as name of another variable. And honestly, that doesn't make sense. The name of a variable is only useful to you as a programmer, not for the end result of the code.
Also be aware that your SQL is vulnerable to SQL injection. Always use parameterized queries!

Related

Return a object in C# [duplicate]

I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.
I tried this method but it's not working:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
How can I do it to retrieve all the other values to the textboxes?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=#fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=#fName"
oCmd.Parameters.AddWithValue("#fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person> .
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
create a class called DbManager:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=#firstname and lastname=#lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = #SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = #fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("#fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case
"DbConnectionString")
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll in c# please

I'm trying to run this program and get this error all the time in con.open() please help me!!!!!!!!
public LinkedList<Station> getAllStation()
{
string conString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=\"C:\\Users\adi\\Documents\\RailDB.mdf\";Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(conString);
con.Open();
string sqlString = "Select s.Id, s.Name, from Stations s;";
SqlCommand com = new SqlCommand(sqlString, con);
SqlDataReader rdr = com.ExecuteReader();
Station s;
LinkedList<Station> st=new LinkedList<Station>();
while (rdr.Read())
{
int id = (Int32)rdr[0];
string name = (string)rdr[1];
s = new Station(name, id);
st.AddLast(s);
}
con.Close();
return st;
}
Remove the comma after s.Name in this line:
string sqlString = "Select s.Id, s.Name, from Stations s;";
It should read:
string sqlString = "Select s.Id, s.Name from Stations s;";
On a side note, your code is not really optimal, as it leaves many resources open until garbage collected that should be closed manually. You might want to change your code to this:
public LinkedList<Station> getAllStation()
{
string conString = "...";
LinkedList<Station> st = new LinkedList<Station>();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlCommand com = new SqlCommand("Select s.Id, s.Name, from Stations s;", con))
using (SqlDataReader rdr = com.ExecuteReader())
{
while (rdr.Read())
{
int id = (Int32)rdr[0];
string name = (string)rdr[1];
st.Add(new Station(name, id));
}
}
}
return st;
}
Also, instead of hardcoding the connection string like you do, I'd suggest to use the SqlConnectionStringBuilder class to make sure you always get valid connection strings.

How to apply National Character set to dynamic query

I am trying to apply N before variable name for Unicode as mentioned in How to use 'LIKE' statement with unicode strings?
With the following code I am getting following error. What need to be corrected here?
Exception: Invalid column name 'N#input'.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
CODE
static void Main(string[] args)
{
string result = DisplayTest("Daily Tax Updates: ----------------- Transactions");
}
private static string DisplayTest(string searchValue)
{
string test = String.Empty;
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#input", "%" + searchValue + "%");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
test = reader.GetString(0);
}
}
}
}
}
return test;
}
I see a few issues.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input";
should be
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE #input";
...
command.Parameters.Add("#input",System.Data.SqlDbType.NVarChar,<<size>>);
command.Parameters[0].Value = "%" + searchValue + "%";
I see you're trying to use a nvarchar parameter. I think .net does that by default with .AddWithValue
I'm not sure why do you need the typecast to nvarchar, you should be fine without the 'N' part.
That part you need when you want to specify that a string literal should be treated as nvarchar not as varchar, as in SELECT * from Table where field like N'%VALUE%'
Otherwise, you just declare your variable/parameter as nvarchar
Taken from this stack Stack overflow
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
Try this one -
private static string DisplayTest(string searchValue)
{
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,* FROM Account WHERE AccountType LIKE #input";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add("#input", SqlDbType.NVarChar);
command.Parameters["#input"].Value = string.Format("%{0}%", searchValue);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
}
return String.Empty;
}

How to retrieve data from a SQL Server database in C#?

I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.
I tried this method but it's not working:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
How can I do it to retrieve all the other values to the textboxes?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=#fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=#fName"
oCmd.Parameters.AddWithValue("#fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person> .
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
create a class called DbManager:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=#firstname and lastname=#lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = #SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = #fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("#fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case
"DbConnectionString")
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}

how to return int value from select query in function?

I need to retrieve Ticket_Id from tbl_Ticket to pass into body section of sending email function..
Is the below code correct?
every times i get Ticket_Id 1..
public int select_TicketId(){
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
int i=cmd1.ExecuteNonQuery();
return i;
}
You are searching for ExecuteScalar which returns the first value.
using System.Configuration;
//
public int select_TicketId()
{
string strConn = ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
return Convert.ToInt32(cmd1.ExecuteScalar());
}
Also use CommandProperties to set the where statement for better security, like below:
public int select_TicketId()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
int result = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd=#email";
command.Parameters.Add("#email", SqlDbType.Text).Value = objNewTic_BAL.email;
result = Convert.ToInt32(command.ExecuteScalar());
}
return result;
}
You should call int i=(int)cmd1.ExecuteScalar(); method
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
You're calling ExecuteNonQuery. But it's a query. This should have rung some warning bells :)
Try ExecuteScalar instead, and cast the result to int...
return (int) cmd1.ExecuteScalar();
Note that you should use using statements for the command and connection as well, so that both are closed appropriately.
And (I hadn't spotted this before) you should definitely use parameterized SQL instead of including a value directly into your SQL. Otherwise you're open to SQL Injection attacks...
So something like:
private const string FetchTicketIdSql =
"select Ticket_Id from tbl_Ticket where Client_EmailAdd = #Email";
public int FetchTicketId()
{
// No need for ToString call...
string connectionString =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(connection, FetchTicketIdSql))
{
command.Parameters.Add("#Email", SqlDbType.NVarChar).Value =
bjNewTic_BAL.email;
return (int) command.ExecuteScalar();
}
}
}
You should consider what you want to happen if there isn't exactly one result though...
Hiral,
ExecuteNonQuery in
int i=cmd1.ExecuteNonQuery();
will return number of records that satisfy your query. In this case it is 1 (or 0 if there are no emails)
Try using ExecuteReader instead.

Categories