How to view data from a database in cmd - c#

Good morning, I'm doing a job where I have to show some information from a database in cmd, I search the internet and only find in Tables DataGrid do not understand how I will do, I have the following code:
public class atm
{
public static void Main()
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;";
cnn = new SqlConnection(connectionString);
try
{
using (SqlCommand cmd = cnn.CreateCommand())
{
cnn.Open();
Console.WriteLine("Is working");
var sqlQuery = "SELECT FirstName FROM tblATM";
using (SqlDataAdapter da = new SqlDataAdapter(sqlQuery, cnn))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
Console.WriteLine(dt);
}
}
}
}
catch (SqlException erro)
{
Console.WriteLine("Is not working" + erro);
}
finally
{
cnn.Close();
}
}
}
When I open it says it's working, then I think the connection is working but it doesn't show the database data I'm asking for. If anyone knows how to help me, i'd appreciate it.

A DataTable is overkill, consider the following to loop through the records.
internal class Program
{
static void Main(string[] args)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
{
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName FROM tblATM" })
{
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
}
Console.ReadLine();
}
}
With last name
using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
{
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName,LastName FROM tblATM" })
{
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"{reader.GetString(0)} {reader.GetString(1)}");
}
}
}

You can use dapper to connect and query data from a database connection.
The below link is the official documentation of dapper
https://www.learndapper.com/ here you can find sample code also.

Related

Nested methods to insert to database in C# is not inserting all the data

I have a service using 3 methods (each one calling another one) to insert data to 3 tables in sql azure. The first two methods insert the data correctly but the third one (the relationship of the other two) which recieves the indexes of the first two tables doesn't. The methods are something like:
public int InsertTableOne([FromBody]Object obj)
{
int IdTableOne = 0;
tring connectionString = WebConfigurationManager.AppSettings["MyString"];
string queryString = "INSERT INTO TableOne (Name,Phone OUTPUT INSERTED.IdTableOne VALUES (#Name,#Phone) ";
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlTransaction tran = connection.BeginTransaction())
{
using (SqlCommand comm = new SqlCommand(queryString, con, tran))
{
try
{
command.Parameters.AddWithValue("#Name", obj.Name);
command.Parameters.AddWithValue("#Phone",obj.Phone);
IdTableOne = Convert.ToInt32(command.ExecuteScalar());
InsertTableTwo(obj,IdTableOne)
tran.Commit();
}
catch()...
finally
{
con.Close();
}
}
}
}
}
public int InsertTableTwo([FromBody] ob obj,List<listOfElements> listofThings,int IdTableOne)
{
int IdTableTwo = 0;
string queryString = "INSERT INTO TableTwo (Car,Color) OUTPUT INSERTED.IdTableTwo VALUES(#Car,#Color)";
string connectionString = WebConfigurationManager.AppSettings["MyString"];
using (SqlConnection con = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand comm = new SqlCommand(queryString, con))
{
try
{
command.Parameters.AddWithValue("#Car","" );
command.Parameters.AddWithValue("#Color", "");
foreach (listOfElements thing in (listofThings))
{
command.Parameters["#Car"].Value = GetCar(thing.Car);//Methodo to get the car, works fine
command.Parameters["#Color"].Value = thing.Color;
IdTableTwo = Convert.ToInt32(command.ExecuteScalar());
InsertTableThree(IdTableOne, IdTableTwo);
}
}
catch()...
}
}
return IdTableTwo;
}
public int InsertTableThree(int IdTableOne,int IdTableTwo)
{
string connectionString = WebConfigurationManager.AppSettings["MyString"];
string queryString = "INSERT INTO TableThree (IdTableOne,IdTableTwo) VALUES(#IdTableOne,#IdTableTwo)";
using (SqlConnection con = new SqlConnection(connectionString))
{
//connection.Open();
using (SqlCommand comm = new SqlCommand(queryString, con))
{
try
{
command.Parameters.AddWithValue("#IdTableOne", IdTableOne);
command.Parameters.AddWithValue("#IdTableTwo", IdTableTwo);
command.Parameters.Clear();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
return IdTableOne;
}
At the end, the first two tables receive the data but the last one remains empty without the indexes. There's no crash with the database, the transaction or the code. The only problem is that last table data. Also when I debug it, the values of the indexes are correct at the time they're supposed to be inserted.
You are just preparing the command in last method but not executing it. Here is the modified version of third method.
public int InsertTableThree(int IdTableOne,int IdTableTwo)
{
string connectionString = WebConfigurationManager.AppSettings["MyString"];
string queryString = "INSERT INTO TableThree (IdTableOne,IdTableTwo) VALUES(#IdTableOne,#IdTableTwo)";
using (SqlConnection con = new SqlConnection(connectionString))
{
//connection.Open();
using (SqlCommand comm = new SqlCommand(queryString, con))
{
try
{
comm.Parameters.AddWithValue("#IdTableOne", IdTableOne);
comm.Parameters.AddWithValue("#IdTableTwo", IdTableTwo);
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
return IdTableOne;
}

Data from SQL reader to datatable - Invalid attempt to call Read when reader is closed

I am keep trying and still don't know how to fix this, keep getting same error. I want to get data from the database to txt file.
using (conn)
{
conn.Open();
SqlCommand cmd = new SqlCommand(command)
cmd.Connection = (SqlConnection)conn;
using (cmd)
{
SqlDataReader reader = cmd.ExecuteReader();
using(reader)
{
while (reader.Read())
{
dt.Load(reader);
}
}
using (StreamWriter sw = new StreamWriter(txtPath.Text + fileName))
{
// write to text file from Datatable dt
} }
Try insted your code, something like this:
DataTable myDataTable = new DataTable();
using (SqlConnection myConnection = new SqlConnection(yourDBconn)
{
yourDBconn.Open();
using (SqlDataAdapter myAdapter = new SqlDataAdapter(strYourQuery, yourDBconn))
{
myAdapter.Fill(myDataTable);
}
}
}
Here you are. Tested.
var customers = new List<Tuple<int, string>>(); // the list of ID, Name
using (var con = new SqlConnection("your connection string"))
{
using(SqlCommand cmd = new SqlCommand("select ID, Name from Customer", con))
{
con.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
customers.Add(new Tuple<int, string>(
(int)reader["ID"], reader["Name"].ToString()));
}
}
}
}
// Store customers to file

How to correctly open and close a SQLite Database in a C# class

Ok so i have a DBConnect class in which I have all my methods relating to the database of my program. I understand that connections are a relatively expensive resource so what is the correct way of opening and closing my database file.
This is what i'm currently using
I simply create the connection in the constructor and then open and close it when needed in the methods. Does this correctly return the connection to the pool? Also would it be better if I put a using(conn) in my methods.
public class DBConnect
{
SQLiteConnection conn = null;
public DBConnect()
{
string connStr = #"Data Source=tests.db; Version=3;";
conn = new SQLiteConnection(connStr);
}
public DBConnect(string connStr)
{
conn = new SQLiteConnection(connStr);
}
public DataTable DBSelect(string query)
{
/*
* Uses a select query to store data from the database into
* a datatable
*/
try
{
conn.Open();
DataTable dt = new DataTable();
using (SQLiteCommand cmd = new SQLiteCommand(query, conn))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
dt.Load(dr);
return dt;
}
}
}
catch (SQLiteException err)
{
MessageBox.Show("Caught exception: " + err.Message);
return null;
}
finally
{
conn.Close();
}
}//DBSelect

How to get list of all database from sql server in a combobox using c#.net

I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}

How to bind a datasource to a label control

It's easy to bind a data source to something like a gridview or repeater, but how would I do it with a label? Heres the sql connection that I want to modify. By the way, I don't need 2 way binding.
public void Sql_Connection(string queryString)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The query I'm using:
SELECT Description FROM RbSpecials WHERE Active=1
public string SqlConnection(string queryString)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = queryString;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// This will return the first result
// but there might be other
return reader.GetString(0);
}
}
return null;
}
}
This will also ensure that in case of exception all disposable objects are disposed and will properly return the SQLConnection to the connection pool in order to be reused.
And finally assign the Text property of the label:
lblTest.Text = SqlConnection("SELECT Description FROM RbSpecials WHERE Active=1");
use ExecuteReader rather than ExecuteNonQuery
public void Sql_Connection(string queryString)
{
using(SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings"RBConnectionString"].ConnectionString))
{
using(SqlCommand cmd = new SqlCommand(queryString, conn))
{
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
lblDescription.Text = rdr.GetString(0);
}
}
}
}
}
using (SqlConnection con = new SqlConnection(Connection_String))
{
SqlCommand cmd = new SqlCommand("select * from Customers", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader adpt = cmd.ExecureReader();
if(rdr.Read())
{
lblName.Text = rdr[0].ToString();
}
}

Categories