Displaying values from a SQL database in C# console application - c#

I am trying to connect to a database in C# and bring up certain data points. The database has numerous columns and tables and I simply want to display them in the console using Writeline(). Below is what I have so far. The code runs without error but does not display anything either.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Sql;
namespace SQLIntro
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection("Server=[SQ_SIXTEEN];Database=[PocketCentral];User ID=[un];Password=[pw];Trusted_Connection=true"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM tbl_Terminal", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
}
Console.WriteLine();
}
}
}
}
}
}
}
The one thing is where the column info would go...The SQL command? or in the while loop?.

That code would actually throw an exception. You have surrounded the names with brackets in your connection string which would cause the connection to fail. Change it to:
using (SqlConnection connection = new SqlConnection("Server=SQ_SIXTEEN;Database=PocketCentral;Trusted_Connection=true"))
Note that when Trusted_Connection is true (windows authentication) you don't use UserID and Password.
EDIT: Additional notes.
You would normally know your data content (your columnname and types). From SQL viewpoint it is suggested that you should list all your columns. ie: Instead of simply using "select *" use something like "select firstName, lastName, ... from ...".
As per the reader, instead of reader.GetValue[i] you use reader[index] and cast the type to what it should be like:
(int)reader[0]
(DateTime)reader["OrderDate"]
Integer indexing is faster but depends on column position where string indexing with column name is more readable.
EDIT2: Don't skip looking into LINQ. It is easier IMHO.

Related

Using Odbc driver query given result in database but not filling datatable in c#, there is no error

Just started using windows 11 and installed Oracle drivers for 32Bit and 64Bit, wrote program using C# to fetch data from Oracle database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.Odbc;
using System.Data;
using System.Data.SqlClient;
namespace ApexAutoEmailConsol
{
static class ServiceLog
{
static String connectionString = "Dsn=Prod21_32;uid=ebseb;pwd=ebseb";
static string strQuery = string.Empty;
public static string OutstandingInvoices()
{
try
{
OdbcConnection oCon = new OdbcConnection();
oCon.ConnectionString = connectionString;
oCon.Open();
DataTable dtSales = new DataTable();
strQuery = "SELECT * from apps.org_organization_definitions HO";
// if I run above query in Toad it's giving result.
OdbcDataAdapter myAdp = new OdbcDataAdapter(strQuery, oCon);
myAdp.Fill(dtSales);
//Adapter not filling data to the datatable.
if (dtSales.Rows.Count <= 0)
{
return "";
}
return strReturn;
}
catch (Exception Ex)
{
WriteErrorLog(Ex.ToString());
return "";
}
}
}
When I copy strQuery and run on Toad, getting result but datatable is still empty.
What is the problem? The same code is working perfect on my Windows10 machine.
UnCOMMITted data is only visible within the session that created it (and will ROLLBACK at the end of the session if it has not been COMMITted). If you can't see the data from another session (C#) then make sure you have issued a COMMIT command in the SQL client (Toad).
If you have issued a COMMIT and still can't see the data then make sure that both the SQL Client (Toad) and the C# program are connecting to the same database and are querying the same user's schema of that database.
It's very unique problem, I had it around 2 years ago with my another machine, where I was not able to get some query result in Toad. Some queries are working but some of with specific table in joing was giving empty result. That time I added following language setting in my environment variable and was worked.
NLS_LANG = American_America.UTF8
Used same in my new machine and now am getting result with Visual Studio 2022.

SQL Server exception 'Must declare the scalar variable "#nameQuery".'

I am creating a practice SQL Server database project, and I'm trying to enter text into a SQL Server database through a Windows Form. I'm not sure if my text data was really entered to my database. How do I view if it was entered? I'm a beginner so please try to use beginner SQL and VS vocabulary. I've tried going to show table data but that shows that no data was entered so I'm assuming its not working. Whenever I hit the button it just gives me no response so I'm not sure.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace DBHotel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Nicholas Hoffs\\source\\repos\\DBHotel\\DBHotel\\Hotel.mdf;Integrated Security=True";
private void instBttn_Click(object sender, EventArgs e)
{
string nameQuery = textInst.Text;
using(SqlConnection conn = new SqlConnection(connectionString))
{
using(SqlCommand cmd = new SqlCommand(nameQuery, conn))
{
conn.Open();
cmd.CommandText = "INSERT INTO Customers(name) VALUES(#nameQuery)";
cmd.Parameters.AddWithValue("nameQuery", nameQuery);
cmd.ExecuteNonQuery();
}
}
}
}
}
Help is very much appreciated, thanks!
I know this is nonintuitive but try using the # inside your AddWithValue:
cmd.Parameters.AddWithValue("#nameQuery", nameQuery);
EDIT: WARNING The below solution is at risk of sql injection, and is highly discouraged.
As you are using direct query in instead of using stored procedure, you can't pass parameter to SQL. Instead of passing parameter try using
cmd.CommandText = "INSERT INTO Customers(name) VALUES('" + nameQuery + "')";
this means we are just concatenating the value of variable "nameQuery" in the query itself. so no need of below statement
cmd.Parameters.AddWithValue("nameQuery", nameQuery);

"Streaming" read of over 10 million rows from a table in SQL Server

What is the best strategy to read millions of records from a table (in SQL Server 2012, BI instance), in a streaming fashion (like SQL Server Management Studio does)?
I need to cache these records locally (C# console application) for further processing.
Update -
Sample code that works with SqlDataReader
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
namespace ReadMillionsOfRows
{
class Program
{
static ManualResetEvent done = new ManualResetEvent(false);
static void Main(string[] args)
{
Process();
done.WaitOne();
}
public static async Task Process()
{
string connString = #"Server=;Database=;User Id=;Password=;Asynchronous Processing=True";
string sql = "Select * from tab_abc";
using (SqlConnection conn = new SqlConnection(connString))
{
await conn.OpenAsync();
using (SqlCommand comm = new SqlCommand(sql))
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
using (SqlDataReader reader = await comm.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
//process it here
}
}
}
}
done.Set();
}
}
}
Use a SqlDataReader it is forward only and fast. It will only hold a reference to a record while it is in the scope of reading it.
That depends on what your cache looks like. If you're going to store everything in memory, and a DataSet is approriate as a cache, just read everything to the DataSet.
If not, use the SqlDataReader as suggested above, read the records one by one storing them in your big cache.
Do note, however, that there's already a very popular caching mechanism for large database tables - your database. With the proper index configuration, the database can probably outperform your cache.
You can use Entity Framework and paginate the select using Take and Skip to fetch the rows by buffer. If you need in memory caching for such a large dataset I would suggest using GC.GetTotalMemory in order to test if there is any free memory left.

How do I create a MySql database connection that returns results to a text file?

I want to write a MySql statement that will connect to the database, select a column from the table, then output that data to a text file to a specific location on my computer. I have searched the internet for a couple days now and don't seem to find the answer I am looking for. I am fairly new to c#, MySql, and Visual Studio. I am just trying to learn how to write the correct statements and get the desired result. Any help would be greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Windows.Forms;
using System.IO;
namespace NewPractice
{
public class Connect
{
static void Main()
{
string results = #"server=111.111.11.111; userid=anyone;
password=anypassword; database=anydatabase";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(results);
conn.Open();
//Console.WriteLine(
File.WriteAllLines(
#"C:\Documents and Settings\anyone\My Documents\Tests\testoutput.txt",
results.ToArray());
}
catch (MySqlException ex)
{
Console.WriteLine("Error: (0)", ex.ToString());
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
}
You're writing the contents of the result string to the file, not the data you're attempting to select. You need to run a sql command and get a SqlDataReader object to write your data to the file.
string results = #"server=111.111.11.111; userid=anyone;
password=anypassword; database=anydatabase";
MySqlConnection connection = new MySqlConnection(results);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "select * from mycustomers";
connection.Open();
reader = command.ExecuteReader();
using(var sw = new StreamWriter("C:\MyPath\MyFile.txt"))
{
while (reader.Read())
{
var row = (IDataRecord)reader;
sw.WriteLine(row["myColumn"]);
}
}
connection.Close();
If the database is on your local machine you can use 'select .. into outfile'. http://dev.mysql.com/doc/refman/5.1/en/select-into.html. This will write to a folder on the server so it's not v useful if it's a different machine and you can't copy from there.
There are plenty of tutorials out there for accessing MySQL from .NET.
This is one: http://zetcode.com/db/mysqlcsharptutorial/
In any language, there are a few simple steps to read from a database:
1. connect to the database.
2. execute a query
3. iterate through the results of the query
4. close the connection.
What you are doing in your code is connecting to the database and then trying to write the connection information to a file.

Windows Search sql - can't access System.Search.QueryFocusedSummary

I'm trying to query the Windows Search 4.0 using sql. The property
of interest for me is: System.Search.QueryFocusedSummary.
I'm trying to read this property from the SystemIndex. I get a "column does not exist" error message. I am able to read other columns such as: System.Search.AutoSummary.
I am using the Microsoft Windows Search 3.x SDK download
(Windows.Search.Interop.dll) on a Windows 7 operating System and Windows
Search 4.0.
My query is:
SELECT TOP 25 System.QueryFocusedSummary From SystemIndex where
CONTAINS('microsoft') ORDER BY System.ItemDate DESC
How can I get the query working with System.Search.QueryFocusedSummary?
The code is as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Security.Permissions;
using System.Text;
using Microsoft.Search.Interop;
namespace QueryFocusedSummaryTest
{
class Program
[Stathread]
static void Main(string[] args)
{
string sqlQuery = "select top 25 System.Search.QueryFocusedSummary from SystemIndex where contains('microsoft') order by System.ItemDate DESC";
CSearchManager manager = new CSearchManager();
ISearchCtalogManager catalogMaager = manager.GetCatalog("SystemIndex");
ISearchQueryHelper queryHelper = catalogManager.GetQueryHelper();
using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString))
{
conn.Open();
using (OleDbCommand command = new OleDbCommand(sqlQuery, conn))
{
OleDbDataAdapter ds = new OleDbDataAdapter(command);
DataSet ds = new DataSet();
ds.Fill(ds);
command.ExecuteNonQuery();
//By now it has thrown the exception saying that the column is not found.
}
}
}
}
Here is a link about columns available for oledb interface:
https://web.archive.org/web/20120615190325/http://www.ariankulp.com/downloads/WindowsShellOLEProperties.txt
Seems System.Search.QueryFocusedSummary is not exposed, while System.Search.AutoSummary is. Maybe that's why you can't get the column.

Categories