Getting unknown data from SQL Server using SqlDataReader - c#

I use this code for getting data from SQL Server:
string rootname = "[" + nameroot + "]";
string retVal = "";
string constring = "Data Source =(Local);Initial Catalog=Tajari;Integrated Security=True;";
SqlConnection conobj = new SqlConnection(constring);
string commandtext = "select distinct " + rootname + " from TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
//retVal = dr[nameroot].ToString();
}
conobj.Close();
Now I need this data inserted into a variable or textbox.
The problem is that my values are unknown

Solution 1 :
You can use Index value.
Try This:
while (dr.Read())
{
retVal = dr[0].ToString();
}
Solution 2 :
You can also use alias name.
string commandtext = "select distinct " + rootname + " as myrootname from
TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
retVal = dr["myrootname"].ToString();
}
Suggestion: Your Query is open to SQL Injection Attacks i would suggest you to use Parameterised Queries to avoid them.
Solution 3: Using Parameterised Queries
if you want to add all rootname values you need to add all values to List.
List<string> list = new List<string>();
string commandtext = "select distinct "+rootname+" as myrootname from
TBLJobsRootName where MenuId between 1 and #countroot";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
comobj.Parameters.AddWithValue("#countroot",countroot);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
lis.Add(dr["myrootname"].ToString());
}
//You can retunrn list

Related

Out of Range Error while accessing date from SQL Server

I want to fetch the maximum value of date from the table. But I always get an 'OutofRangeException' error. I changed my query several times.
Due_Date column has date data type
Due_Date_Sample is a string var
Due_Date_var is a DateTime var
My code:
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') FROM Transactions WHERE Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}
You need to give an alias to the selected value, e.g.: FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date
You can do this:
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date FROM Transactions where Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}

Display database values in textbox

I have a datatable with 2 columns, ID and Name, I have populated my combobox with the column ID.
string Query = "SELECT * FROM [Database]";
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
me.Open();
OleDbDataReader reader = constr.ExecuteReader();
while(reader.Read())
{
textBox15.Text = (reader["Name"].ToString());
}
reader.Close();
When I select an item from the combobox, I want to retrieve values from the Column Name in the same row. For instance I select a value from my combobox which is in datarow 1 and it matches the datarow 1 in the table Name
Is there anyway to do this?
I am currently here
{
string Query = "SELECT * FROM [Database] where Name ='" + comboBox6.Text + "' "; string y = textBox15.Text
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
me.Open();
OleDbDataReader reader = constr.ExecuteReader();
constr.Parameters.Add(new OleDbParameter("#Name", y));
while (reader.Read())
{
textBox15.Text = reader["Name"].ToString();
}
me.Close();
}
}
I am still getting an error "No parameters given for one or more values" I am sure that the code is right.
You'll need to add a parameter to your SQL query. For example:
string myName = myComboBox.SelectedItem.Text;
string Query = "SELECT * FROM [Database] WHERE Name = ?";
OleDbConnection conn = new OleDbConnection(connection);
OleDbCommand cmd = new OleDbCommand(Query, conn);
cmd.Parameters.Add(new OleDbParameter("#name", myName));
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while(reader.Read())
etc...
I'm not sure of the exact syntax for the OLE DB .NET Provider, but hopefully this helps somewhat.

How to get all table names ans schemas without loop

I have to retrieve the names and the schemas of old tables for creating the new tables in new database within a program. I wrote this procedure which is working. In first part I get the names of tables and store it in MyArray and the in second part I put this names in query string. But in the second part I get in first read the name of table and the following data is the schema.
Is there a solution like this:(this is not working I tried :)
MySqlCommand cmd = new MySqlCommand("SHOW * CREATE TABLE " + DbName, conn);
My function is there:
private int CopySchemas(string pathname)
{
string [] MyArray = new string[11];
int index = 0;
using (MySqlConnection conn = new MySqlConnection(connstr))
{
using(MySqlCommand cmd = new MySqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='" + DbName+"'",conn))
{
conn.Open();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MyArray[index] = reader.GetValue(0).ToString();
++index;
}
reader.Dispose();
}
catch (MySqlException e)
{
MessageBox.Show(e.Number.ToString() + " -> " + e.Message.ToString());
return 0;
}
}
for (int i = 0; i < MyArray.Length; ++i)
{
string tblname = MyArray[i];
string fname = pathname +"\\" + tblname + ".sql";
MySqlCommand cmd = new MySqlCommand("SHOW CREATE TABLE " + DbName + "." + tblname, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string fname = pathname +"\\" + reader.GetValues(0) + ".sql";
string schema = reader.GetValue(1).ToString();
File.WriteAllText(fname,schema);
}
reader.Dispose();
}
}
return index;
}
Finally I sawed that for each connection must have only one reader.
So I opened two connections and for each connection I associated a reader. So I don't use an array for storing the tables names I use only the second reader where I get the tables names and schemas.
Here is the code:
private int CopySchemas(string pathname)
{
int index = 0;
MySqlConnection conn1 = new MySqlConnection(PublicVariables.cs);
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='" + PublicVariables.DbName + "'", conn))
{
conn.Open();
conn1.Open();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string tblname = reader.GetValue(0).ToString();
MySqlCommand cmd1 = new MySqlCommand("SHOW CREATE TABLE " + PublicVariables.DbName + "." + tblname, conn1);
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string fname = pathname + "\\" + reader1.GetValue(0).ToString() + ".sql";
string schema = reader1.GetValue(1).ToString();
File.WriteAllText(fname, schema);
}
reader1.Dispose();
++index;
}
}
catch (MySqlException e)
{
MessageBox.Show(e.Number.ToString() + " -> " + e.Message.ToString());
return 0;
}
}
}
return index;
}

How can I get the value of 2 columns, not only one?

I want the result of two columns and not only one. I tried:
MessageBox.Show(reader.GetString("traceid", "idref"));
But it does not work. I am a beginner with C#, can anyone please help?
String str = #"server=localhost;database=asianimport;userid=tera;password=******;";
MySqlConnection con = null;
try
{
con = new MySqlConnection(str);
con.Open(); //open the connection
MessageBox.Show("connect " );
String cmdText = "SELECT * FROM tracerecord limit 3";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader.GetString("traceid", "idref"));
}
}
Do a GetString() twice, one per field:
while (reader.Read())
{
String traceID = reader.GetString("traceid");
String idRef = reader.GetString("idref");
MessageBox.Show(traceID + " - " + idRef);
}
reader.GetString() returns the result from only one column of your current record. Use them separatly for each colunm with concatanation:
MessageBox.Show(reader.GetString("traceid")+ " "+reader.GetString("idref"));

Display SQL query result in a label in asp.net

I'm trying to display the SQL query result in a label but it's not showing. This is my code:
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
showresult.ExecuteNonQuery();
string actresult = ((string)showresult.ExecuteScalar());
ResultLabel.Text = actresult;
conn.Close();
Need help please. Thanks!
Try this one.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
Is there a typo in there? You have two calls to the database:
showresult.ExecuteNonQuery();
This won't return a value and I'm not sure why you would have it there
string actresult = ((string)shresult.ExecuteScalar());
Unless you have a shresult variable, this query should error. What is the shresult variable?
Use SqlParameter to filter the result and call ExecuteScalar() or ExecuteReader() method.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID=#ID";
SqlCommand showresult = new SqlCommand(result, conn);
// If ID is int type
showresult.Parameters.Add("#ID",SqlDbType.Int).Value=ID.Txt;
// If ID is Varchar then
//showresult.Parameters.Add("#ID",SqlDbType.VarChar,10).Value=ID.Txt;
conn.Open();
string actresult = (string)showresult.ExecuteScalar();
conn.Close();
if(!string.IsNullOrEmpty(actresult))
ResultLabel.Text = actresult;
else
ResultLabel.Text="Not found";
using (SqlConnection conn = new SqlConnection(connectionString))
{
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = #id";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.Parameters.AddWithValue("id", ID.Text);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
}
This will dispose the connection and has no string concatenation in the query.
conn.Open();
string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.ExecuteNonQuery();
int actresult = ((int)showresult.ExecuteScalar());
ResultLabel.Text = actresult.Tostring();
conn.Close();

Categories

Resources