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());
}
}
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.
So I'm trying to create a website with a database and currently just wanting to check the database connnection by printing a number from the database in the HTML code. I'm terrible at scripts so please ignore that.
The C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class LogFiller
{
public int userID;
string connectionstring = "USER ID=x;" +
"PASSWORD=x;server=x;" +
"Trusted_Connection=yes;" +
"database=x; " +
"connection timeout=30";
public LogFiller()
{
//
// TODO: Add constructor logic here
//
}
public int getUserID
{
get {
using (var connection = new SqlConnection(connectionstring))
{
try
{
connection.Open();
SqlCommand myCommand = new SqlCommand("SELECT ID FROM x WHERE Name = 'x'", connection);
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
adapter.Fill(dt);
return (int)dt.Rows[0][0];
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
return userID;
}
}
}
The script I thought of (but doesn't work)
#{
LogFiller lf = new LogFiller();
lf.getUserID;
}
For clarification: I want to just write the number that the C# code returns anywhere on my page.
Once you open a C# block with the #{ }, in order to write the value from a variable inside that block you need to escape it with another # like this:
#{
LogFiller lf = new LogFiller();
<p>User ID: #lf.getUserID</p>
}
Also, as someone in a comment stated, you'll likely need to fully qualify your LogFiller type with the namespace. So WhateverYourNamespaceIs.LogFiller
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
I have encountered a problem with getting locked out of SQLite file.
I am currently working on employee register for my company and use SQLite as a database of choice. From my program, I populated the database using scripts I prepared. Reading goes well and all, but once I make any change to the employee at all, the program freezes at "database is locked" exception.
I created a static class called SQLiteManager where I have all methods involving the DB. I then call them from Windows Forms like
foreach (Employee em in SQLiteManager.getEmployees()){
//filling the fields }
calls
public static List<Employee> getEmployees() {
List<Employee> ret = new List<Employee>();
SQLiteDataReader reader;
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = "select ID_Employee from Employee";
reader = cmd.ExecuteReader();
while (reader.Read()) { ret.Add(extractEmployee(reader["ID_Employee"].ToString(), false)); }
}
return ret;
}
I always use this "using" notations in ALL other methods that call ExecuteReader() in them.
Method that I use to crunch the script and populate the DB:
public static bool processSqlCommandFile(string file)
{
try
{
using (StreamReader sr = new StreamReader(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = line;
cmd.ExecuteNonQuery();
}
}
sr.Close();
}
}
catch (Exception ex)
{
return false;
}
return true;
}
and finally, the sore method
public static bool alterEmployee(Employee e) {
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = "Update Employee SET name = '"+e.name+"' where ID_Employee = "+e.id;
//Alter the command once this shiet works
cmd.ExecuteNonQuery();
}
return true;
}
Yet it always gets frozen. By using the using(SQLiteConnection...) I thought I am getting rid of the "sleepy" connections that would somehow lock it, but the trouble is somewhere else.
Can you help me identify the problem or tell me steps to identify it myself?
Thank you