How to separate retrieved information from a select statement - c#

I'm currently trying to get information from my sql database and separate it so it displays the information like so:
1)
2)
3)
etc...
Right now when I run the program the songs titles come back on their own line, but I want them numbered. I'm pulling song titles with a select statement and storing them in a string. How can I choose which title I want to put in my writeline? Is there a way for me to store it in a string array?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data;
namespace Databasetesting
{
class Play
{
//finding an artists
public static void FindArtist()
{
//servere connection
string cs = #"server=192.168.0.10;userid=dbsAdmin1903;password=password;database=Music_Mixer;port=8889";
MySqlConnection conn = null;
MySqlDataReader rdr = null;
//prompt for artist
string Art = PromptArtist();
try
{
//call in database
conn = new MySqlConnection(cs);
//open connection
conn.Open();
//Statement
String cmdText = "SELECT song_title FROM songs WHERE artist = #uI LIMIT 15";
//make a new command
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
//binding
cmd.Parameters.AddWithValue("#uI", Art);
//make reader = to new command
rdr = cmd.ExecuteReader();
//if something is not found
while (!rdr.HasRows)
{
Console.WriteLine("\r\nSorry, we could find that Artist.");
Console.WriteLine("Would you like to try again?!");
Menu.menu();
}
//run the reader and display to user
Console.Clear();
Console.WriteLine($"Here are 15 songs by {Art}!");
while (rdr.Read())
{
//store song titles and display to user
string Songs;
Songs = rdr["Song_title"].ToString();
Console.WriteLine (Songs);
}
//run the play again method
Console.Write("Press ENTER to continue...");
Console.ReadLine();
Console.WriteLine("What would you like to do?");
Menu.again();
}
catch (MySqlException er)
{
Console.WriteLine(er);
}
finally
{
if (conn != null)
{
conn.Close();
}
Console.ReadLine();
}
}
}

If I undestood correct
List<string> songsTitles = new List<string>();
while (rdr.Read())
{
//store song titles and display to user
string song = rdr["Song_title"].ToString();
Console.WriteLine(song);
songsTitles.Add(song);
}
var numberedSongs = songsTitles.Select((obj, index) => new {Index = index, Obj = obj}).ToArray();
string[] numberedSongsString = songsTitles.Select((obj, index) => $"{index}) {obj}").ToArray();

You can use an auxiliar datatable, something like this:
DataTable dt = new DataTable();
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
dt.Load(cmd.ExecuteReader());
if(dt.Rows.Count != 15){
//error code
}else{
foreach(DataRow row in dt.Rows){
Console.WriteLine(row["Song_title"].ToString());
}
}

Related

Trying to make a user input go through a LIKE SQL statement

Currently working on music guessing program. I have the user input lyrics and the program will try to find a match. If the program finds ones it will display the artist name. At the moment I am running trying to run a SELECT statement to find the most relevant match. When I hard code the element the console will give me the artists, but when I try to set it as the user input it displays nothing.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data;
namespace Databasetesting
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start\n");
// MySQL Database Connection String
string cs = #"server=192.168.0.5;userid=***;password=***;database= Music_Mixer;port=8889";
// set up connection
MySqlConnection con = null;
// make a reader
MySqlDataReader reader = null;
Console.WriteLine("Please enter song lyrics:");
string uI = Console.ReadLine();
// write a try catch statement
try
{
// cal in database
con = new MySqlConnection(cs);
// open connection
con.Open();
// Statement
String cmdText = "SELECT Artist FROM Songs WHERE Lyrics LIKE ('%#uI%')";
// make a new command
MySqlCommand cmd = new MySqlCommand(cmdText, con);
// binding
cmd.Parameters.AddWithValue("#uI", uI);
// make reader = to new command
reader = cmd.ExecuteReader();
// run the reader and display to user
while (reader.Read())
{
string Artists = reader["Artist"].ToString();
Console.WriteLine(Artists);
}
}
catch(MySqlException er)
{
Console.WriteLine(er);
}
finally
{
if(con != null)
{
con.Close();
}
Console.ReadLine();
}
}
}
}
Do this instead
string uI = "%" + Console.ReadLine() + "%";
you can also do string interpolation
string uI = $"%{Console.ReadLine()}%";
And your SQL statement
String cmdText = "SELECT Artist FROM Songs WHERE Lyrics LIKE #uI";
You can use string concatenation on the named parameter. In MySql you can try the concat operator || (depending on version, config ) or the concat function
isntead of ...LIKE ('%#uI%') go for ... LIKE concat('%',#uI,'%')
SELECT Artist FROM Songs WHERE Lyrics LIKE concat('%',#uI,'%')

how to convert all tables from SDF file together to csv file in c# or any application which converts

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlServerCe;
namespace ExportSDF
{
class Program
{
static void Main(string[] args)
{
SqlCeConnection conn = null;
SqlCeCommand cmd = null;
SqlCeDataReader rdr = null;
try
{
conn = new SqlCeConnection(#"Data Source = C:\Program Files\Microsoft SQL Server Compact Edition\v3.1\SDK\Samples\Northwind.sdf;max database size=256");
conn.Open();
cmd = new SqlCeCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader();
System.IO.TextWriter stm = new System.IO.StreamWriter(new System.IO.FileStream(#"C:\customers.csv", System.IO.FileMode.Create), Encoding.Default);
while (rdr.Read())
{
for (int i = 0; i < rdr.FieldCount-2; i++)
{
if (rdr[i] != null)
{
stm.Write(rdr[i].ToString());
stm.Write(";");
}
else
{
stm.Write(";");
}
}
if (rdr[rdr.FieldCount-1] != null)
{
stm.Write(rdr[0].ToString());
}
stm.Write(System.Environment.NewLine);
}
stm.Close();
rdr.Close();
cmd.Dispose();
}
finally
{
// Close the connection when no longer needed
//
conn.Close();
}
}
}
}
this program is not working please help me with a code or application which converts all the table together to csv file.i have some application which converts only one table at a time.i cannot select multiple table.
From what I can see, you got the code from here.
Could you please be clear on what does not work? What have you tried so far?
It seems to me that you only copied the code but didn't change the Data Source, which obviously won't work for you.
Thanks.

get all row and column data using SELECT - C#

I'm trying to get all data from an SQL table and store it in a List using the C# programming language.
the SQL statement I'm using is:
private string cmdShowEmployees = "SELECT * FROM Employees;";
This is being used in the same class as a function
public List<string> showAllIdData()
{
List<string> id = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
id.Add(reader[0].ToString());
}
return id;
}
}
and here
public List<string> showAllActiveData()
{
List<string> active = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
active.Add(reader[1].ToString());
}
return active;
}
I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.
I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Any ideas?
If you must use the reader in this way, why not create an object which holds the table row data.
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
That way you can loop through with your reader as follows:
public List<SomeComplexItem> showAllActiveData()
{
List<SomeComplexItem> active = new List<SomeComplexItem>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
var someComplexItem = new SomeComplexItem();
someComplexItem.SomeColumnValue = reader[1].ToString();
someComplexItem.SomeColumnValue2 = reader[2].ToString();
someComplexItem.SomeColumnValue3 = reader[3].ToString();
active.Add(someComplexItem);
}
return active;
}
You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult();.
The database used is the standard Microsoft NorthWind database.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace SQL_Server_TwoList
{
public class DataOperations
{
public List<string> Titles { get; set; }
public List<string> Names { get; set; }
/// <summary>
/// Trigger code to load two list above
/// </summary>
public DataOperations()
{
Titles = new List<string>();
Names = new List<string>();
}
public bool LoadData()
{
try
{
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"
SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees];
SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Names.Add(reader.GetString(0));
}
// move on to second select
reader.NextResult();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Titles.Add(reader.GetString(0));
}
}
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Form code
namespace SQL_Server_TwoList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataOperations dataOps = new DataOperations();
if (dataOps.LoadData())
{
listBox1.DataSource = dataOps.Names;
listBox2.DataSource = dataOps.Titles;
}
}
}
}
You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.
Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
conn = new SqlConnection(Connstr);
try
{
string contents = "SELECT * FROM ..."
conn.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn); //create command using contents of sql file
da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds
DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database
try
{
//manipulate database
da_1.Fill(ds_1);
if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
{
for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
{
//rows[rownumber][column number/ "columnName"]
Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
}
}
}
catch(Exception err)
{}
conn.Close();
}
catch(Exception ex)
{}

System index out range exception C#

I have the following code:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimeClock
{
class Company
{
DataTable rows = new DataTable();
public Company()
{
MySqlConnection connection = null;
try
{
string connectionString = TimeClock.Properties.Settings.Default.timeclockConnectionString;
connection = new MySqlConnection(connectionString);
connection.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM companies WHERE ID = #ID LIMIT 1", connection);
command.Parameters.AddWithValue("#ID", TimeClock.Properties.Settings.Default.CompanyID);
MySqlDataAdapter da = new MySqlDataAdapter(command);
da.Fill(rows);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine(ex);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
public String getName()
{
DataRow row = rows.Rows[0];
return row["company_name"].ToString();
}
}
}
I know why I'm getting this error: say that no records were found in the database, the of course row[0] will no exist, hence the exception. But how do I deal with when there are no records to store in the Datatable? By the way, I'm quite new to C# and any input would be great; feel free to criticize.
Before you access a collection
DataRow row = rows.Rows[0];
you'll have to make sure that the item exists:
if(rows.Count > 0)
DataRow row = rows.Rows[0];
always
You must change getName function.
public String getName()
{
if (rows.Rows != null && rows.Rows.Count > 0)
{
DataRow row = rows.Rows[0];
return row["company_name"].ToString();
}
return string.Empty;
}
To read data from SQL I'm doing it like so:
using (SqlCommand SelectCommand = new SqlCommand(strbSelect.ToString()))
{
SelectCommand.Parameters.AddWithValue("Asset", AssetNumber);
SelectCommand.Parameters.AddWithValue("Subnumber", Subnumber);
SelectCommand.Connection = new SqlConnection(GetConnectionString());
SelectCommand.Connection.Open();
using (SqlDataReader Reader = SelectCommand.ExecuteReader())
{
if (Reader.HasRows)
{
while (Reader.Read())
{
if (Reader[0] != DBNull.Value)
{
ReturnValue = Reader.GetBoolean(0);
}
}
}
else
return false;
}
SelectCommand.Connection.Close();
}
StrbSelect is a StringBuilder.

SQL to Arduino via C♯

As part of a project I'm putting together, I have an Arduino updating a MySQL database via C♯ and, in another location I have another C♯ program doing a simple SELECT query on the database, and communicating its findings to another Arduino via Serial. I have written most of the code for this second program but am having some annoying issues at the end of it all.
Below is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Xml;
using System.IO.Ports;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string hkday;
string hkall;
//SERIAL
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.NewLine = "\n";
//OPEN SERIAL
serialPort1.Open();
//SQL
string connString = "Server=xxxx;Uid=xxxx;Password=xxxx;Port=xxxx;Database=xxxx;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command1 = conn.CreateCommand();
command1.CommandText = "Select USERS from HK where UPTIME='HKDAY'";
MySqlCommand command2 = conn.CreateCommand();
command2.CommandText = "Select USERS from HK where UPTIME='HKALL'";
//EXECUTE QUERIES
if (_continue = true)
{
conn.Open(); //Connect
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
//Write to value and string
Console.WriteLine(reader1["USERS"].ToString());
hkday = reader1["USERS"].ToString();
}
Console.ReadLine();
_continue = false;
conn.Close(); //Disconnect
}
else
{
conn.Open(); //Connect
MySqlDataReader reader2 = command1.ExecuteReader();
while (reader2.Read())
{
//Write to console and string
Console.WriteLine(reader2["USERS"].ToString());
}
hkall = reader2["USERS"].ToString();
Console.ReadLine();
_continue = true;
conn.Close(); //Disconnect
//WRITE STRINGS TO SERIAL
serialPort1.WriteLine(
String.Format(hkday, hkall));
}
serialPort1.Close();
}
public static bool _continue { get; set; }
}
}
I can't work out how my section titled WRITE STRINGS TO SERIAL needs to be syntaxed and placed within the code to be able to reference both 'hkday' and 'hkall'
My 'if (_continue = true)' flag doesn't seem to work, and I'm not sure why.
I think that if these two issues are solved, the program ought to work, can you see any other glaring issues?
Thank you, I know these are only tiny issues, but I can't seem to work them out.
Potentially important: I'm trying to get the output as '123,456\n' as my arduino program already recognises this as its input.
UPDATE
Having received the answers I have, I have compounded this project with the other one I'm currently doing to try and have an arduino update a MySQL database via C# and then also have it download the table's data that it isn't updating to display out through another arduino.
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.IO.Ports;
using MySql.Data.MySqlClient;
namespace SQL_Scraper
{
public partial class Sandro : Form
{
//Serial Settings
SerialPort UNO = new SerialPort("COM4", 9600);
SerialPort MEGA = new SerialPort("COM3", 9600);
//Incoming Data String
string RxString;
//Int for download
int? vnday = 0;
int? vnall = 0;
public Sandro()
{
InitializeComponent();
//Open UNO port
UNO.Open();
//Open MEGA Port
MEGA.Open();
}
private void MEGA_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
}
private void Sandro_FormClosing(object sender, FormClosingEventArgs e)
{
if (UNO.IsOpen | MEGA.IsOpen)
{
UNO.Close();
MEGA.Close();
}
}
private void DisplayText(object sender, EventArgs e)
{
}
private void Begin_Click(object sender, EventArgs e)
{
//Turn off start button
Begin.Enabled = false;
//?
this.Invoke(new EventHandler(DisplayText));
//Create Event Handler if data is receiverd
MEGA.DataReceived += new SerialDataReceivedEventHandler(MEGA_DataReceived);
string SQLString = "Server=benchmarkcount.db.9506323.hostedresource.com;Uid=benchmarkcount;Password=Watercress2428;Port=3306;Database=benchmarkcount;";
MySqlConnection SQLConnection = new MySqlConnection(SQLString);
//Receive data
RxString = MEGA.ReadExisting();
//Append Serial Input to Output box)
outputBox.AppendText(RxString);
//Get Unsaved input from text box
string input = outputBox.Text;
string[] inputLines = input.Split('\n');
//Upload findings from MEGA to SQL
foreach (string line in inputLines)
{
if (line.EndsWith("\r")) //Makes sure line is complete
{
if (line.StartsWith("Today's total users: "))
{
string dayUsers = line.Substring(20).Trim();
MySqlCommand UpdateHKDAY = SQLConnection.CreateCommand();
UpdateHKDAY.Parameters.AddWithValue("param1", dayUsers);
UpdateHKDAY.CommandText = "UPDATE HK SET USERS=?param1 WHERE UPTIME='HKDAY'";
SQLConnection.Open();
UpdateHKDAY.ExecuteNonQuery();
SQLConnection.Close();
}
else if (line.StartsWith("All-time total users: "))
{
string allUsers = line.Substring(21).Trim();
MySqlCommand UpdateHKALL = SQLConnection.CreateCommand();
UpdateHKALL.Parameters.AddWithValue("param2", allUsers);
UpdateHKALL.CommandText = "UPDATE HK SET USERS=?param2 WHERE UPTIME='HKALL'";
SQLConnection.Open();
UpdateHKALL.ExecuteNonQuery();
SQLConnection.Close();
}
}
}
//Only keep unparsed text in text box
outputBox.Text = inputLines[inputLines.Length - 1];
//Download Numbers Query
MySqlCommand DownUsers = new MySqlCommand("Select USERS, UPTIME from VN where UPTIME IN ('VNDAY', 'VNALL')", SQLConnection);
//Open Connection
SQLConnection.Open();
//Execute Downloading Numbers
MySqlDataReader theResults = DownUsers.ExecuteReader();
while (theResults.Read())
{
switch (theResults["UPTIME"] as string)
{
case "VNDAY":
vnday = theResults["USERS"] as int?;
break;
case "VNALL":
vnall = theResults["USERS"] as int?;
break;
}
}
//Do things with the results
UNO.WriteLine(String.Format("{0},{1}", vnday, vnall));
Console.WriteLine(String.Format("{0},{1}", vnday, vnall));
//Close Connection
SQLConnection.Close();
}
private void Sandro_Load(object sender, EventArgs e)
{
}
private void Cease_Click(object sender, EventArgs e)
{
Begin.Enabled = true;
Cease.Enabled = false;
}
}
}
However, I would like to be able to check this data - the data being sent to the arduino - in my inputBox to make sure it's in the format "vnday, vnall\n"
Your question and example has too many contradictions. It appears that you are under impression that there is static persistence between separate app runs. There isn't. All your static variables will be cleared with each run. It would be different if you had a method that you called in a loop inside the same app domain.
Also, judging by your variable names and your output requirement, the USERS field is a numeric.
So, assuming you have following table:
USERS UPTIME
------ ------
123456 HKALL
234567 HKDAY
following code:
public static void Main()
{
int? hkday = 0;
int? hkall = 0;
using (MySqlConnection conn = new MySqlConnection("..."))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select USERS, UPTIME from HK where UPTIME IN ('HKDAY', 'HKALL')", conn);
MySqlDataReader reader = cmd.ExecuteReader();
//this assumes that there is only one record per 'HKDAY' and 'HKALL',
//otherwise the last value will be stored
while (reader.Read())
{
switch (reader["UPTIME"] as string)
{
case "HKDAY":
hkday = reader["USERS"] as int?;
break;
case "HKALL":
hkall = reader["USERS"] as int?;
break;
}
}
}
Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}
will output:
234,567
123,456
Or if you desire to run independent queries:
private static int? GetUSERS(string hkval)
{
using (MySqlConnection conn = new MySqlConnection("..."))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select USERS from HK where UPTIME=#hkval", conn);
cmd.Parameters.AddWithValue("hkval", hkval);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
return reader["USERS"] as int?;
return null;
}
}
public static void Main()
{
int hkday = (int)GetUSERS("HKDAY");
int hkall = (int)GetUSERS("HKALL");
Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}
You could also pass HKDAY/HKALL as a parameter to you app using args.
I'm not a C programmer but know a lot of serial ports, I suppouse that this solves your first issue.
//WRITE STRINGS TO SERIAL
serialPort1.Write(hkday); // do not append line feed
serialPort1.WriteLine(hkall); // append line feed

Categories

Resources