Validating Database Input C# Access Oledb - c#

I am very new to C# and need a little bit of help on validating the input that can be added to the access database before it is inserted.
Most of the validations will be if something has not been entered then a message box will appear saying 'nothing entered' or if something needs more characters then 'length too short'. How could i achieve something like this?
Here is my code:
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;
using System.Data;
namespace ClassLibrary2
{
public class Class1
{
OleDbConnection connection;
OleDbCommand command;
private void ConnectTo()
{
connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\CMS\CustomerDatabase.accdb;Persist Security Info=False");
command = connection.CreateCommand();
}
public Class1()
{
ConnectTo();
}
public void Insert(Customer p)
{
try
{
command.CommandText = "INSERT INTO CustomerData ([Forename], [Surname], [Email Address], [Home Phone Number], [Mobile Phone Number], [Address], [AreaTown], [County], [Postcode]) VALUES('" + p.Forename1 + "', '" + p.Surname1 + "', '" + p.EAddress1 + "', '" + p.HomePhone1 + "' , '" + p.MobNum1 + "' , '" + p.Address1 + "', '" + p.AreaTown1 + "', '" + p.County1 + "', '" + p.Postcode1 + "')";
command.CommandType = CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
public List<Customer> FillComboBox()
{
List<Customer> CustomersList = new List<Customer>();
try
{
command.CommandText = "SELECT * FROM CustomerData";
command.CommandType = CommandType.Text;
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Customer p = new Customer();
p.Id = Convert.ToInt32(reader["ID"].ToString());
p.Forename1 = reader["Forename"].ToString();
p.Surname1 = reader["Surname"].ToString();
p.EAddress1 = reader["Email Address"].ToString();
p.HomePhone1 = reader["Home Phone Number"].ToString();
p.MobNum1 = reader["Mobile Phone Number"].ToString();
p.Address1 = reader["Address"].ToString();
p.AreaTown1 = reader["AreaTown"].ToString();
p.County1 = reader["County"].ToString();
p.Postcode1 = reader["Postcode"].ToString();
CustomersList.Add(p);
}
return CustomersList;
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
public void Update(Customer oldCustomer, Customer newCustomer)
{
try
{
command.CommandText = "UPDATE CustomerData SET [Forename] = #newCustomer.Forename1, [Surname] = #newCustomer.Surname1, [Email Address] = #newCustomer.EAddress1, [Home Phone Number]= #newCustomer.HomePhone1, [Mobile Phone Number] = #newCustomer.MobNum1, [Address]= #newCustomer.Address1, [AreaTown] = #newCustomer.AreaTown1, [County]= #newCustomer.County1, [Postcode]= #newCustomer.Postcode1 WHERE [ID] = #oldCustomer.Id";
command.Parameters.AddWithValue("#Forename", newCustomer.Forename1);
command.Parameters.AddWithValue("#Surname", newCustomer.Surname1);
command.Parameters.AddWithValue("#Email Address", newCustomer.EAddress1);
command.Parameters.AddWithValue("#Home Phone Number", newCustomer.HomePhone1);
command.Parameters.AddWithValue("#Mobile Phone Number", newCustomer.MobNum1);
command.Parameters.AddWithValue("#Address", newCustomer.Address1);
command.Parameters.AddWithValue("#AreaTown", newCustomer.AreaTown1);
command.Parameters.AddWithValue("#County", newCustomer.County1);
command.Parameters.AddWithValue("#Postcode", newCustomer.Postcode1);
command.Parameters.AddWithValue("#ID", oldCustomer.Id);
command.CommandType = CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
Thanks for your help, im really struggling

If you want to archive this try to Implement a function that check every validation before you execute the save function
hope following sample function will give you an idea
private bool CheckValidation( )
{
bool returnBool = true;
if ( string.IsNullOrWhiteSpace(txtName.txt) )
{
//Show a label next to you text box
returnBool = false;
}
return returnBool;
}
If your return value is true save the data to data base using SP
Hope this will guide you. for extra information have you aware with SQLHelper class. It will make your life easier, therefore you don't need to implement connection and SP calls every where. if not let me know will send you sample project.
welcome to .NET world
regards,
Pubudu

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;
using System.Data;
namespace DAL
{
public static class CustomerDAL
{
public static void Insert(Customer p){.......}
public static List<Customer> FillComboBox(){......}
public void Update(Customer oldCustomer, Customer newCustomer){.......}
}
}
----------------------------------------------------
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;
using System.Data;
namespace BAL
{
public class Customer
{
public int Id {get;set;}
public string Name {get;set;}
.......................
.......................
}
}
------------------------------------------------------
In UI Create a Windows or Web Form and add buttons and textbox and on buttonSave_Click event
If(txtName.Text=="")
{
MessageBox.Show("Some text", "Some title",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtName.Focus();
}
else
{
//calling BAL
var cus=new Customer{
Name=txtName.Text
}
//Calling DAL
CustomerDAL.Insert(cus);
MessageBox.Show("Information", "Record saved successfully inti the database.",
MessageBoxButtons.OK, MessageBoxIcon.Information);
txtName.tex="";
}
Hope this will help you.
Create a solution,give it a proper name.Then inside the solution create two assembles projects BAL and DAL.If you are still confused about assembles then avoid creating assemblies and following link might help you.
http://www.tutorialized.com/tutorial/3-Tier-Architecture-in-asp.net-using-c/67931

Validation of user input regarding length, patterns, text versus numbers, etc. should be done before your code gets near the data layer.
This is what regular expressions are great at. There is a ton of information on using them, so I won't try to repeat here. Just bingoogle regular expressions and you will find a wealth of info.

Related

How to fix Error in argument exception system

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.SqlClient;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pwnew.PasswordChar = '*';
pwtxt.PasswordChar = '*';
signup.Visible = false;
}
private void signupbtn_Click(object sender, EventArgs e)
{
signup.Visible = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (unnew.Text != null && pwnew.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
MessageBox.Show("Error");
}
}
private void loginbtn_Click(object sender, EventArgs e)
{
if (untxt.Text != null && pwtxt.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT COUNT (*) FROM userTable where username = '" + untxt.Text + "' and password '" + pwtxt.Text + "'", obj.conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
Form2 meLoad = new Form2();
meLoad.Visible = true;
this.Hide();
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
obj.conn.Close();
MessageBox.Show("Successfully Login");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("No empty fields are allowed");
}
{
}
}
}
}
Hi, I am completely new to c#, im having this error whenever i click sign up. It tells me to check the line 44 which is
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
Im a student, adn dont have enough background in programming, i'd appreciate someone's help. I really want to learn this programming language, and im currentlty having troubles.enter image description here Thank u so much.
I use this for Connection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
class Connect
{
public SqlConnection conn = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public string locate = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\hp\source\repos\WindowsFormsApp1\WindowsFormsApp1\UserDB.mdf;'Integrated Security=True";
}
}
It seems something is breaking to connect your database.
Please double check your connection string,If you need help for connection string, you may visit https://www.connectionstrings.com/
This tutorial may be helpful for you to connect database using c#.
https://www.guru99.com/c-sharp-access-database.html

This code shows me that "CommandText has not been initialized"

I want to check ManagerUsername and ManagerEmail in the database and the display a messagebox to show the user with their password.But when I execute the code it shows me that:
"commandtext has not been initialized"
so I want to know how can I fix my code to display what I want. And also a way to improve my code to work more efficient
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.SqlClient;
namespace Cybertronics
{
public partial class passwordRecovery : Form
{
int pin = 0;
private int _failedAttempts = 0;
public passwordRecovery()
{
InitializeComponent();
}
private void passwordRecovery_Load(object sender, EventArgs e)
{
lblAttempt.Visible = false;
}
private void btnBackLogin_Click(object sender, EventArgs e)
{
loginFrm loginForm = new loginFrm();
this.Hide();
loginForm.Show();
}
private void btnSubmitEmail_Click(object sender, EventArgs e)
{
try
{
string emailAddress = txtEmail.Text;
string username = txtManagerUsername.Text;
string password = "ChangeMe";
CyberDatabase db = new CyberDatabase();
db.OpenConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Parameters.AddWithValue("#ManagerUsername", username);
cmd.Parameters.AddWithValue("#ManagerEmail", emailAddress);
db.SetSqlCommand(cmd);
reader = db.Select();
cmd.CommandText = "SELECT ManagerUsername from tblManagers WHERE ManagerUsername = #ManagerUsername and ManagerEmail = #ManagerEmail";
db.SetSqlCommand(cmd);
reader = db.Select();
if (reader.HasRows)
{
reader.Read();
SqlCommand passwordUpdate = new SqlCommand();
passwordUpdate.CommandText = "UPDATE tblManagers SET ManagerPassword=#Password WHERE ManagerUsername=#ManagerUsername and ManagerEmail=#ManagerEmail";
db.SetSqlCommand(passwordUpdate);
MessageBox.Show("your new password is:" + password);
}
else
{
if (pin != 21)
{
_failedAttempts++;
MessageBox.Show("Wrong password or username fail to login. you have" + (3 - _failedAttempts) + " attempts more.", "EPIC FAIL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
if (_failedAttempts == 3)
{
Application.Exit();
}
}
}
}
catch (SqlException sql)
{
CyberMethods.DisplayErrorMessage(sql.Message);//error message from cybermethods class for DB
}
catch (Exception exc)
{
CyberMethods.DisplayErrorMessage(exc.Message);//error message from cybermethods class
}
}
}
}
your code is very messy and untidy. It is very error prone. Check the below sample code for best practices.
using (connection)
using (SqlCommand command = new SqlCommand(
"SELECT ManagerUsername from tblManagers WHERE ManagerUsername = #ManagerUsername and ManagerEmail = #ManagerEmail",
connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
}
}
you have multiple query statements. for the seperation of duties principles I suggest you to make 3 functions each seperate and call them respectively.
and It is wise to keep connection open then then close when all the operations finish.
For solving your error
before your first db.SetSqlCommand(cmd); just add your query statement with
cmd.CommandText = "select ....." ;

Only one record written to sql server + combobox not refreshed

I'm new to .net programming and I have a problem writing intput from a form to sql server. Only one record gets written to the database, for the other records it's says "Data not written to database.". Also my cmbbox is not updated after the data is written to the database, though I run method UpdateInitialWeek().
I don't want to write 'spaghetti code' and would love my program to be a structured one. So any advice is greatly appreciated (I already know it's better to use the Entity Framework to deal with data, something I will learn eventually ;)).
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.SqlClient;
namespace Write_to_database
{
public partial class WriteToDatabase : Form
{
SqlServer sql = new SqlServer();
public WriteToDatabase()
{
sql.OpenSqlConnection();
InitializeComponent();
this.UpdateInitialWeek();
sql.CloseSqlConnection();
}
private void btnWrite_Click(object sender, EventArgs e)
{
WriteToOutput(sql.OpenSqlConnection());
if (txtMilitaryPress.Text != "")
WriteToOutput(sql.InsertToTraining(ConvertDate(dtMilitaryPress.Value), "Military Press", txtMilitaryPress.Text.ToString(), txtRepMilitaryPress.Text.ToString(), cmbMilitaryPress.Text.ToString()));
if (txtDeadlift.Text != "")
WriteToOutput(sql.InsertToTraining(dtDeadlift.Value.ToString(), "Deadlift", txtDeadlift.Text.ToString(), txtRepDeadlift.Text.ToString(), cmbDeadlift.Text.ToString()));
if (txtBenchPress.Text != "")
WriteToOutput(sql.InsertToTraining(dtBenchPress.Value.ToString(), "Bench Press", txtBenchPress.Text.ToString(), txtRepBenchPress.Text.ToString(), cmbBenchPress.Text.ToString()));
if (txtBackSquat.Text != "")
WriteToOutput(sql.InsertToTraining(dtBackSquat.Value.ToString(), "Back Squat", txtBackSquat.Text.ToString(), txtRepBackSquat.Text.ToString(), cmbBackSquat.Text.ToString()));
this.UpdateInitialWeek();
WriteToOutput(sql.CloseSqlConnection());
}
//Write output to textbox
public void WriteToOutput(string output)
{
this.txtOutput.AppendText(output + Environment.NewLine);
}
//Convert date for sql server
public string ConvertDate(DateTime date)
{
return date.ToString("MM/dd/yyyy");
}
//Update comboboxes to set right training week
public void UpdateInitialWeek()
{
this.cmbBackSquat.Text = CheckWeek(sql.GetDataTraining("Back Squat"));
this.cmbBenchPress.Text = CheckWeek(sql.GetDataTraining("Bench Press"));
this.cmbDeadlift.Text = CheckWeek(sql.GetDataTraining("Deadlift"));
this.cmbMilitaryPress.Text = CheckWeek(sql.GetDataTraining("Military Press"));
}
//Training week +1 except for week 4 --> back to 1
public string CheckWeek(string trainingWeek)
{
int trWeek = Int32.Parse(trainingWeek);
if (trWeek == 4)
trWeek = 1;
else
trWeek += 1;
return trWeek.ToString();
}
}
public class SqlServer
{
SqlConnection con = new SqlConnection("Data Source=WINSERVER;Initial Catalog=TRAINING;Integrated Security=SSPI;");
public string OpenSqlConnection()
{
try
{
con.Open();
return "Connection to: " + "'Data Source=WINSERVER;Initial Catalog=TRAINING;Integrated Security=SSPI;'" + " successful.";
}
catch
{
return "Connection to: " + "'Data Source=WINSERVER;Initial Catalog=TRAINING;Integrated Security=SSPI;'" + " failed.";
}
}
public string CloseSqlConnection()
{
try
{
con.Close();
return "Connection to: " + "'Data Source=WINSERVER;Initial Catalog=TRAINING;Integrated Security=SSPI;'" + " successfully closed";
}
catch
{
return "Connection to: " + "'Data Source=WINSERVER;Initial Catalog=TRAINING;Integrated Security=SSPI;'" + " not closed.";
}
}
public string InsertToTraining(string date, string lift, string weight, string reps, string week)
{
try
{
using (SqlCommand command = new SqlCommand("INSERT INTO LIFT_HISTORY VALUES(#date,#lift,#weight,#reps,#week)", con))
{
command.Parameters.Add(new SqlParameter("weight", weight.ToString())); //SqlDbType.NVarChar
command.Parameters.Add(new SqlParameter("date", date.ToString()));
command.Parameters.Add(new SqlParameter("week", week.ToString()));
command.Parameters.Add(new SqlParameter("reps", reps.ToString()));
command.Parameters.Add(new SqlParameter("lift", lift.ToString()));
command.ExecuteNonQuery();
}
return "Data successfully written to database.";
}
catch
{
return "Data not written to database.";
}
}
public string GetDataTraining(string where)
{
int trainingWeek;
//using (SqlCommand command = new SqlCommand("SELECT WEEK_OF_TRAINING FROM dbo.LIFT_HISTORY WHERE [DATE] = (SELECT MAX([DATE]) FROM dbo.LIFT_HISTORY WHERE LIFT = 'Deadlift') AND LIFT = 'Deadlift')", con))
using (SqlCommand command = new SqlCommand("SELECT WEEK_OF_TRAINING FROM dbo.LIFT_HISTORY WHERE LIFT = '"+ where +"' ORDER BY [DATE] DESC", con))
{
trainingWeek = (Int32)command.ExecuteScalar();
}
return trainingWeek.ToString();
}
}
}
There are some issues with your code, but it's ok for now that you still learning, for example:
public WriteToDatabase()
{
sql.OpenSqlConnection();
InitializeComponent();
this.UpdateInitialWeek();
sql.CloseSqlConnection();
}
should be:
public void WriteToDatabase()
{
sql.OpenSqlConnection();
InitializeComponent();
this.UpdateInitialWeek();
sql.CloseSqlConnection();
}
That's because you're not returning anything, instead of that you shoud to declare the type of variable that you're returning on.
Well first of all I'd like to suggest you to use a layer-oriented coding. For example:
I'll start crating an entity class:
namespace Entities
{
public class LiftingStory
{
public string Weight { get; set; }
public string Date { get; set; }
public string Week { get; set; }
public string Reps { get; set; }
public string Lift { get; set; }
}
}
Then you start creating "Data-Access" Layer
using System.Data;
using System.Configuration;
using Entities;
namespace DataAccess
{
public class DataLiftingStory
{
public bool insertLifting(LiftingStory obj) //correction: should be LiftingStory instead of DataLiftingStory because I'm retrieving a LiftingStory objecto to be proccesed.
{
//we're creating a new connection to Database, but it will need string parameter
//you can get it directly from the connectionstring on the Web.config in this way
// ConfigurationManager.ConnectionStrings["nameParameterOfYourConnString"].ConnectionString
//instead of that I'll do it with a string for making more easier to understand
string connectionString = "Data Source=WINSERVER;Initial Catalog=TRAINING;Integrated Security=SSPI;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//now I'll create the command
using (SqlCommand command = new SqlCommand())
{
//so now I've to say what type of command I'm making up. In your case is "Text" because you're being explicit with the query
//I suggest you to use stored procedures btw.
command.CommandType = CommandType.Text;
//now the command text will be your query
command.CommandText = "INSERT INTO LIFT_HISTORY VALUES(#date,#lift,#weight,#reps,#week)";
//now we set the parameters
command.Parameters.Add(new SqlParameter("date", obj.Date));
command.Parameters.Add(new SqlParameter("lift", obj.Lift));
command.Parameters.Add(new SqlParameter("weight", obj.Weight));
command.Parameters.Add(new SqlParameter("reps", obj.Reps));
command.Parameters.Add(new SqlParameter("week", obj.Week));
try
{
command.Connection = connection;
command.Connection.Open();
//now we're executing the query and if we get more than 0 that will means that it inserted or modified a row
//then it will return true and going out from method.
if (command.ExecuteNonQuery() > 0)
return true;
}
catch (Exception)
{
//If it fails return false
return false;
throw;
}
finally
{
//then we close the connection
command.Connection.Close();
}
//if not failed but it didn't anything, it will return false
return false;
}
}
}
Now it's the easy part Business.
using System.Web;
using Entities;
using DataAccess;
namespace Business
{
public class BusinessLiftingStory
{
public bool insertLifting(LiftingStory obj)
{
DataLiftingStory dataLifting = new DataLiftingStory();
dataLifting.insertLifting(obj);
}
}
}
So the last step is to fill the object in the "View-layer" and call the method from Business:
LiftingStory obj = new LiftingStory();
obj.Weight = string.Empty;
obj.Date = string.Empty; //put values from comboBoxes
obj.Reps = string.Empty;
obj.Lift = string.Empty;
obj.Week = string.Empty;
BusinessLiftingStory busObj = new BusinessLiftingStory();
busObj.insertLifting(obj);
Combo boxes are not refreshing data because the DataBind() method, dont forget in the moment when you want to "redraw" your comboBox you'll have to set DataSource = null then get the datasource again and then dataBind.
use a method Init() for that if you want.
private void Init()
{
cmbWeight.DataSource = null;
cmbWeight.DataSource = //new Datasource
//dont forget to set the values and text fields
cmbWeight.DataBind();
}
In that way you'll have a order in your code, , I hope it would help you.
Greetings :)
PS: sorry for the extended answer.
maybe try printing out the exception details either to your return string or console, etc.
instead of
catch
{
return "Data not written to database.";
}
..
catch( Exception ex )
{
return "Data not written to database." + ex.Message;
}
..
https://msdn.microsoft.com/en-us/library/system.exception.message(v=vs.110).aspx

SqlCeDataReader Read() returning false

I am working on a card game which uses a database to store and retrieve cards. Unfortunately I am having trouble retrieving data from the database.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CardGame
{
class Program
{
static void Main(string[] args)
{
Card c = new Card();
Card d;
c.Name = "TestCard";
c.Pack = "Pack";
c.Value = 5;
c.Color = Colors.green;
c.Description = "Describing stuff";
//Database.CreateCardTable(); (Already created)
Database.InsertCard(c);
d = Database.RetrieveCard("TestCard");
Console.WriteLine(d.Name);
Console.ReadLine();
}
}
}
Database.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;
using System.Data;
using System.Data.SqlClient;
namespace CardGame
{
class Database
{
public static void CreateCardTable()
{
string sqlStr;
SqlCeConnection CardConn = new SqlCeConnection(Properties.Settings.Default.CardsConnectionString);
sqlStr = "CREATE TABLE Data " +
"(Name NVARCHAR(50), " +
"Pack NVARCHAR(50), " +
"Value INT, " +
"Color INT," +
"Description NVARCHAR(200))";
SqlCeCommand CardComm = new SqlCeCommand(sqlStr, CardConn);
try
{
CardConn.Open();
CardComm.ExecuteNonQuery();
Console.WriteLine("Tables Created Successfully!");
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Error creating tables.");
}
finally
{
if (CardConn.State == ConnectionState.Open)
{
CardConn.Close();
}
}
}
public static void InsertCard(Card c)
{
SqlCeConnection CardConn = new SqlCeConnection(Properties.Settings.Default.CardsConnectionString);
try
{
CardConn.Open();
SqlCeCommand insertCommand = new SqlCeCommand("INSERT INTO Data VALUES(#Name, #Pack, #Value, #Color, #Description)", CardConn);
insertCommand.Parameters.Add("Name", c.Name);
insertCommand.Parameters.Add("Pack", c.Pack);
insertCommand.Parameters.Add("Value", c.Value);
insertCommand.Parameters.Add("Color", c.Color);
insertCommand.Parameters.Add("Description", c.Description);
Console.WriteLine("Card inserted successfully");
}
catch
{
Console.WriteLine("Some kind of error.");
}
finally
{
if (CardConn.State == ConnectionState.Open)
{
CardConn.Close();
}
}
}
public static Card RetrieveCard(string name)
{
Card c = new Card();
SqlCeConnection CardConn = new SqlCeConnection(Properties.Settings.Default.CardsConnectionString);
try
{
CardConn.Open();
SqlCeCommand retrieveCommand = new SqlCeCommand("SELECT * FROM Data WHERE Name=#Name", CardConn);
retrieveCommand.Parameters.Add("Name", name);
SqlCeDataReader reader = retrieveCommand.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("Reader: " + reader["Name"].ToString());
c.Name = (string)reader["Name"];
//read rest
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return c;
}
public void CreateAccountDB(string DBName)
{
}
}
}
When I run insert card I do get a success message (at the end of the try statement). When I do Database.RetrieveCard("TestCard"); it reaches the line while (reader.Read()) but my program does not reach the code inside of the while statement. How can I fix my code so that I can read cards from the database?
I built the command to insert a card into the database but I never actually executed it. So nothing was ever inserted so when I go to retrieve the card it will return nothing because there is nothing in the database!
I changed
try
{
CardConn.Open();
SqlCeCommand insertCommand = new SqlCeCommand("INSERT INTO Data VALUES(#Name, #Pack, #Value, #Color, #Description)", CardConn);
insertCommand.Parameters.Add("Name", c.Name);
insertCommand.Parameters.Add("Pack", c.Pack);
insertCommand.Parameters.Add("Value", c.Value);
insertCommand.Parameters.Add("Color", c.Color);
insertCommand.Parameters.Add("Description", c.Description);
Console.WriteLine("Card inserted successfully");
}
to
try
{
CardConn.Open();
SqlCeCommand insertCommand = new SqlCeCommand("INSERT INTO Data VALUES(#Name, #Pack, #Value, #Color, #Description)", CardConn);
insertCommand.Parameters.Add("Name", c.Name);
insertCommand.Parameters.Add("Pack", c.Pack);
insertCommand.Parameters.Add("Value", (int)c.Value);
insertCommand.Parameters.Add("Color", (int)c.Color);
insertCommand.Parameters.Add("Description", c.Description);
insertCommand.ExecuteNonQuery();
Console.WriteLine("Card inserted successfully");
}

Showing the output query?

I'm trying to show the output of the query SELECT * FROM phpbb_topics
I'm running this from a C# console app, using the MySql connector api.
The query works fine when I run it phpmyadmin, and gives me a list of forum topics.
When I run it in the C# app remotely though, it doesn't seem to do anything.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql;
using MySql.Data;
namespace SqlConsoleSlr
{
class Program
{
static void Main(string[] args)
{
MySql.Data.MySqlClient.MySqlConnection mycon =
new MySql.Data.MySqlClient.MySqlConnection(GetConnectionString());
Console.WriteLine(GetConnectionString());
if (mycon.State != System.Data.ConnectionState.Open)
try
{
mycon.Open();
Console.WriteLine("we're in");
}
catch (System.Data.SqlClient.SqlException ex)
{
Console.WriteLine(ex);
}
MySql.Data.MySqlClient.MySqlCommand msc = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM `phpbb_topics` ");
Console.WriteLine("completed"); /// gets to here, but doesn't show output of msc
Console.ReadLine();
}
public static string GetConnectionString()
{
string hostname = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;";
string username = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx;";
string dbname = "xxxxxxxxxxxxxxxxxxxxxxxx;";
string password = "xxxxxxxxxxxxxxxxxxxxxxxxxxx;";
string s = "Server=" + hostname + "User=" + username + "Database=" + dbname + "Password=" + password;
return s;
}
}
}
Is there some method I need to call on the query object?
The only one I could find is msc.BeginExecuteReader();, but that doesn't seem to change the execution either.
You will need to create a MYSQL Data Reader object.
MySql.Data.MySqlClient.MySqlDataReader read = msqlCommand.ExecuteReader();
and then you can output the records after you read.read() all of the records.
You have to create an object of MySQL Data Reader then execute the command.
MySql.Data.MySqlClient.MySqlCommand msc = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM `phpbb_topics` ");
MySql.Data.MySqlClient.MySqlDataReader read = msqlCommand.ExecuteReader();
if(read != null)
{
//Sample output
while (read.Read())
{
int TopicID = Convert.ToInt32(read["Topic_ID"]);
string TopicName = Convert.ToString(read["Topic_Name"]);
Console.WriteLine(TopicID.ToString() + " : " + TopicName);
}
}

Categories