c# query to txt - c#

I was reading the example here:
https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx
And wanted to do a test reading that select and writing it into a file:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
System.IO.File.WriteAllText(#"C:\stupidtest\customers.txt", reader.ReadToEnd());
sqlConnection1.Close();
But i can't because 'SqlDataReader' does not contain a definition for 'ReadToEnd' and no extension method 'ReadToEnd' accepting a first argument of type 'SqlDataReader' could be found.
So how can i get that simple select into a txt file with an output like this one?
dasdgdsgsdg asgasg sadgasdgasdg agdsfg
sdasdgasdgasgg sdfasdfa sadfasdfasdgasdgasdg sadgasgdgda
a asd gdgasdg asdfgghh
If i use:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\stupidtest\customers.txt"))
{
while (reader.HasRows)
{
while (reader.Read())
{
file.WriteLine(reader.GetString());
}
reader.NextResult();
}
could i achieve it?

something like this:
static string ReadToEnd(this SqlDataReader rdr){
StringBuilder MyStringBuilder = new StringBuilder();
while (rdr.Read())
{
String line = "";
for(int i=0;i<rdr.FieldCount;i++)
{
line+=rdr.GetString(i)+#"\t";
}
MyStringBuilder.AppendLine(line);
}
return MyStringBuilder.ToString();
}

Related

How can I create a "dynamic" list in C# from query with properties named like columns of a SQL Server table

I want to try this: every time that I execute a query, I want to automatically create a list of objects, every property of the object must be called the same as the column name of table.
Something like this:
my_Sql_table:
code
number
brand
001
43
qwe
002
721
plo
My C# controller:
SqlConnection sqlConn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandText = "select * from my_Sql_table";
cmd.CommandType = CommandType.Text;
sqlConn.ConnectionString = _configuration["dbConnectionString"];
using (sqlConn)
{
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// the code here
}
}
In C#, my result will be this:
myList:
[0] code: "001", number: "43", brand: "qwe"
[1] ....
Now imagine have many queries to do with a large number of columns, my goal is not to create so many models, and read properties more easily when I use javascript.
You may want to change this according to your output format, but this is an idea of how to go about getting your result. I am using Dictionary with ExpandoObject to override the limit on variable allocations. Also try implementing a DataTable instead of reading directly from a SqlDataReader as this tends to cause problems.
using System.Dynamic;
private IEnumerable<ExpandoObject> GetQueryToList()
{
SqlConnection sqlConn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandText = "select * from my_Sql_table";
cmd.CommandType = CommandType.Text;
sqlConn.ConnectionString = _configuration["dbConnectionString"];
using (sqlConn)
{
var list = new List<ExpandoObject>();
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var expandoObject = new ExpandoObject();
for (var i = 0; i<reader.FieldCount; i++)
{
((IDictionary<string, object>) expandoObject).Add(
reader.GetName(i), reader[i]);
}
list.Add(expandoObject);
}
}

Read data from all rows from Oracle and display in textbox using C#

I have Oracle data like this:
The table is named KETERANGAN and I want those data in textBox1. Not just one row but all rows. This my code used OracleDataReader
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOTES FROM KETERANGAN";
cmd.Connection = koneksidb.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["NOTES"].toString();
}
dr.Close();
I get: You're Cool.
I want: You're Cool, Amazing, Wonderful
use += instead of = which will append the result. you are currently replacing it.
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOTES FROM KETERANGAN";
cmd.Connection = koneksidb.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text += dr["NOTES"].toString() + ",";
}
dr.Close();
It could be done like this:
// wrap IDisposable into using
using (OracleCommand cmd = new OracleCommand()) {
cmd.Connection = koneksidb.con;
// Make SQL readable
cmd.CommandText =
#"SELECT Notes
FROM Keterangan";
// wrap IDisposable into using; do not close manually - dr.Close()
using (OracleDataReader dr = cmd.ExecuteReader()) {
// do not append string in loop - use SringBuilder
StringBuilder sb = new StringBuilder();
while (dr.Read()) {
if (sb.Length > 0) // <- do not put delimiter before the very first item
sb.Append(", "); // <- do you want a delimiter? Say, comma?
// ".ToString()" provides debug info, use Convert.ToString() instead
sb.Append(Convert.ToString(dr.GetValue(0)));
}
// Assign data once in order to prevent re-painting (and blinking)
textBox1.Text = sb.ToString();
}
}
Hope, the comments inside the routine explain the code enough.
Safe and optimized solution...
var notesBuilder = new StringBuilder();
const string SQL = #"SELECT NOTES FROM KETERANGAN";
using (var cmd = new OracleCommand(SQL, koneksidb.con))
{
using (OracleDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
notesBuilder.Append(dr["NOTES"]);
notesBuilder.AppendLine(",");
}
}
}
textBox1.Text = notesBuilder.ToString();
Or you can set the Multiline property on your textbox to true and use
textBox1.Lines.Add(dr["NOTES"].toString());

Retrieving values from DB to Label in C#

I have created an Entity Framework application to retrieve Database values but i want to show them in individual labels instead of a gridview??
EmployEntities2 fd = new EmployEntities2();
int idToupdate = Convert.ToInt32(TextBox1.Text);
var jj = (from bn in fd.Contacts
where bn.Id == idToupdate
select bn);
GridView1.DataSource = jj;
GridView1.DataBind();
Established a connection
SqlConnection con = new SqlConnection("CONNECTION_STRING);
SqlCommand cmd = new SqlCommand();
and then,
cmd.CommandText = "select * from table where Condition ;
cmd.Connection = con
Label1.text = ((string)cmd.ExecuteScalar());
Try this one..
You should use SQLDataReader class. Base on what type of data you have in structure you should call a different method of the SQLDataReader object. For example, if you need to retrieve an integer value and display it in a label, this is the code sinppet to do it:
string queryString = "SELECT integer_value FROM table_name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = reader.getSqlInt32(0).ToString();
}
reader.close();
}
This is the best I can do since you didn't provide additional info.
Check out this link for info on SqlDataReader class: SqlDataReader reference

simplify OleDbDataReader code

I made a program, that reads data in the database I use the OleDbDataReader but the problem is I have different tables, this codes works perfectly but I found it a little bit "hardcoded" or recursive here is my sample code
private void loadMilk()
{
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand("select* from Milk", cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
Milk.Add(reader["Product"].ToString());
}
cn.Close();
}
I need to repeat this again and again just to read what's on the other table (e.g., "select* from Fruit then "select* from Classics....) Is there any way so that I will not repeat this code again and again?
thanks.:)
You can refactor that method into something like this:
private IList<string> Load(string tableName, string columnName)
{
var result = new List<string>();
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(string.Format("select* from {0}", tableName), cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
result.Add(reader[columnName].ToString());
}
cn.Close();
return result;
}
Your code sample will be:
var milkItems = Load("Milk", "Product");
var classicItems = Load("Classics", "..."); //Enter the column here.
Edit:
You might want something a little more specific (eg. storing a List<SomeObject> instead of just List<string>). Let's suppose you sometimes you want to return a list of Person, and also you want to read a list of Building. Then you can write something like this (not compiled & tested):
private IList<T> Load<T>(string tableName, Func<OleDbDataReader, T> selector)
{
IList<T> result = new List<T>();
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(string.Format("select* from {0}", tableName), cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
result.Add(selector(reader));
}
cn.Close();
return result;
}
and you can call it like:
Func<OleDbDataReader, Person> selector = x => new Person { Name = x["Person"].ToString() };
Load("People", selector);
private void loadMilk(string TableName, string itemValue)
{
string SQLString = String.Format("select * from {0}",TableName);
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(SQLString, cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
Milk.Add(reader[ItemValue].ToString());
}
cn.Close();
}
Not sure what type "Milk" is.
Try:
private void loadObjectsFrom(string tableName, object obj, string column)
{
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand("select* from " + tableName, cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
obj.Add(reader[column].ToString());
}
cn.Close();
}
Just pass a table name as a parameter:
private void loadMilk(string tableName)
{
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(string.Format("select* from {0}",tableName), cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
Milk.Add(reader["Product"].ToString());
}
cn.Close();
}

MySqlCommand().ExecuteReader().GetString() does not work

I'm working with MySql in C# language.
I'm trying get some data out of my database.
The fields are organized like:
foo baa
38737 22222
I need to get value of foo if my hash is equal to baa
I tried this:
My code(not working)
MySqlConnection con = new MySqlConnection("Server=localhost;Database=test;Uid=user;Pwd=pass;");
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = string.Format("SELECT * FROM info WHERE baa = '{0}'", Hash); ;
cmd.Connection = con;
MySqlDataReader reader = cmd.ExecuteReader();
String res = reader.GetString(0);
I'm getting the following error:
Invalid attempt to access a field before calling Read()
Can someone point out my error?
Thanks in advance.
You are missing a reader.Read() call:
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
String res = reader.GetString(0);
//...
}
Try:
string res;
using(MySqlDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
res = reader.GetString(0);
else
res = "not found";
}
If you change the SQL command to return a single value, for example:
"SELECT foo FROM info WHERE baa = '{0}' LIMIT 1"
then you can also use cmd.ExecuteScalar():
string res = cmd.ExecuteScalar().ToString();

Categories