Interacting with SQL Server database in Visual Studio 2015 - c#

I realise this question could be quite broad but ive been searching for the past 2 days with no luck.
I've created a project in Visual Studio 2015 and created a new data source in that project using a cloud database created with SQL Server Management Studio.
I'm now trying to code a login page in the project, which gets a username and password from 2 textboxes on the UI and executes an SQL query to check if the user exists in the database and if their password is right.
I'm familiar with Java code for database connections, such as the prepared statement and resultset functions.
Is there something equivalent for C#?
Thank you, reference to helpful articles or code samples will be greatly appreciated.

I think this can help you :-
http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program

here is probably the fastest but not the best way to check it.
string yourConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Users.accdb; Persist Security";
using (OleDbConnection conn = new OleDbConnection(yourConnectionString))
{
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("Select * from UsersTable where UName = #Username and Pass = #Password"))
{
cmd.Parameters.AddWithValue("#Username", txtUserName.Text);
cmd.Parameters.AddWithValue("#Password", txtPass.Text);
using (OleDbDataReader r = cmd.ExecuteReader())
{
if (r.HasRows)
{
Console.WriteLine("User exists")
}
else
{
Console.WriteLine("User does not exist")
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}

Related

C# connect to MySQL and read data

So I have this website that people can shop online, but I want to make a software that will read the MySQL database for new orders and when a new order is placed, the software should display the order in some sort of a list. I am using wordpress for this website and there is a button to mark the order as completed, so i also want to have that little button in my program. Any help from where I should be starting ? Thank you!
Kindly do some research work before ask Any question. This may help u.
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=xxxx;uid=xxx;" +
"pwd=xxxx;database=xxx;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}

Adding data to a Microsoft's SQL Server file using c#

I have added a Microsoft's SQL Server file to my project and I am running an SqlCommand to insert my data into the file. I am using System.Data.SqlClient;. The following code is how I add data to my file. After my program finished running then I go to the Data Explorer in my project and ask to Show Table Data of HistQuote and nothing show up. Could anyone advice on how I can verify that my INSERT statement is working.
using (SqlConnection connection = new SqlConnection(Settings.Default.StorageConnectionString))
{
connection.Open();
for (int intCurrentQuote = 0; intCurrentQuote < this.clbStockSelect.CheckedItems.Count; ++intCurrentQuote)
{
for (int intCurrentDate = 0; intCurrentDate < Quotes[intCurrentQuote].HistStockDate.Count; ++intCurrentDate)
{
string strInsert = "INSERT INTO [HistQuote] ";
string strColumns = "(Symbol, [Date], [Open], High, Low, Volume, Adj_Close, [Close]) ";
string strValues = "VALUES (#Symbol, #Date, #Open, #High, #Low, #Volume, #Adj_Close, #Close)";
using (SqlCommand sqlCommand = new SqlCommand(strInsert + strColumns + strValues, connection))
{
sqlCommand.Parameters.Clear();
sqlCommand.Parameters.Add(new SqlParameter("#Symbol", SqlDbType.NChar));
sqlCommand.Parameters.Add(new SqlParameter("#Date", SqlDbType.DateTime));
sqlCommand.Parameters.Add(new SqlParameter("#Open", SqlDbType.Real));
sqlCommand.Parameters.Add(new SqlParameter("#High", SqlDbType.Real));
sqlCommand.Parameters.Add(new SqlParameter("#Low", SqlDbType.Real));
sqlCommand.Parameters.Add(new SqlParameter("#Close", SqlDbType.Real));
sqlCommand.Parameters.Add(new SqlParameter("#Volume", SqlDbType.Real));
sqlCommand.Parameters.Add(new SqlParameter("#Adj_Close", SqlDbType.Real));
sqlCommand.Parameters["#Symbol"].Size = 10;
sqlCommand.Prepare();
sqlCommand.Parameters["#Symbol"].Value = this.Quotes[intCurrentQuote].HistSymbol;
sqlCommand.Parameters["#Date"].Value = this.Quotes[intCurrentQuote].HistStockDate[intCurrentDate];
sqlCommand.Parameters["#Open"].Value = this.Quotes[intCurrentQuote].HistOpen[intCurrentDate];
sqlCommand.Parameters["#High"].Value = this.Quotes[intCurrentQuote].HistHigh[intCurrentDate];
sqlCommand.Parameters["#Low"].Value = this.Quotes[intCurrentQuote].HistLow[intCurrentDate];
sqlCommand.Parameters["#Close"].Value = this.Quotes[intCurrentQuote].HistClose[intCurrentDate];
sqlCommand.Parameters["#Volume"].Value = this.Quotes[intCurrentQuote].HistVolume[intCurrentDate];
sqlCommand.Parameters["#Adj_Close"].Value = this.Quotes[intCurrentQuote].HistAdjClose[intCurrentDate];
sqlCommand.ExecuteNonQuery();
sqlCommand.Parameters.Clear();
}
}
}
connection.Close();
}
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. Storage)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=Storage;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Would something like this possibly work?
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dataread
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection(Settings.Default.StorageConnectionString))
{
connection.Open();
string strCmd = "Select * from [HistQuote]";
using (SqlCommand sqlCommand = new SqlCommand(strCmd, connection))
{
var rdr = new SqlDataReader();
rdr = sqlCommand.ExecuteReader();
while(rdr.Read())
{
Console.WriteLine(rdr["Symbol"].ToString() + rdr["Date"].ToString() + rdr["Open"].ToString() + rdr["High"].ToString() + rdr["Low"].ToString() + rdr["Volume"].ToString() + rdr["Adj_Close"].ToString() + rdr["Close"].ToString());
}
}
connection.Close();
}
}
}
}

Struggling to insert record into "SQL Server Compact 4.0 Database" from my C# WinForm Application. (I'm using VS 2010))

In my C# Winform Application I have written a code to insert record into the "SQL Server Compact 4.0 Database". Also I had debug code line-by-line everything is working fine (without any error) but after insert functionality when I checked my database I found that record is not inserted into the database, I'm strange why it is happening..!
But I think it is happening because, "when I tried to add database in my project I got this error" Following is my code to insert record into the database--
// Retrieve the connection string from the settings file.
string conString = Properties.Settings.Default.snda_dbConnectionString;
//string conString = "Data Source=|DataDirectory|\\db_snda.sdf";
try
{
conString = conString +";Password = test#1;";
// Open the connection using the connection string.
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
// Read in all values in the table.
using (SqlCeCommand cmd = new SqlCeCommand("INSERT INTO tbl_user_master" + "(user_id, password, user_type, user_title, first_name, middle_name, last_name, gender, dob, mobile_no, email_id, plant_code, div_code, region_code, reporting_to, releaving_date, created_date)" + " VALUES(#user_id, #password, #user_type, #user_title, #first_name, #middle_name, #last_name, #gender, #dob, #mobile_no, #email_id, #plant_code, #div_code, #region_code, #reporting_to, #releaving_date, #created_date)", con))
{
cmd.Parameters.AddWithValue("#user_title", strTitle);
cmd.Parameters.AddWithValue("#first_name", strFirstName);
cmd.Parameters.AddWithValue("#middle_name", strMiddleName);
cmd.Parameters.AddWithValue("#last_name", strLastName);
cmd.Parameters.AddWithValue("#gender", strGender);
cmd.Parameters.AddWithValue("#user_type", strUserType);
cmd.Parameters.AddWithValue("#plant_code", strPlantCode);
cmd.Parameters.AddWithValue("#div_code", strDivCode);
cmd.Parameters.AddWithValue("#region_code", strRegionCode);
cmd.Parameters.AddWithValue("#reporting_to", strReportingTo);
cmd.Parameters.AddWithValue("#user_id", strUserName);
cmd.Parameters.AddWithValue("#password", Encrypt(strPassword)); //Encrypt(strPassword)
cmd.Parameters.AddWithValue("#email_id", strEmailId);
cmd.Parameters.AddWithValue("#mobile_no", strMobileNo);
cmd.Parameters.AddWithValue("#dob", strDOB);
cmd.Parameters.AddWithValue("#created_date", strCreatedDate);
cmd.Parameters.AddWithValue("#releaving_date", strReleavingDate);
cmd.ExecuteNonQuery();
}
con.Close();
XtraMessageBox.Show("User Created Successfully.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
ResetAfterSubmit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Thank you...!
It is hapening because you mix up databases - the one you check is not the one that is used during insert as likely when you start the debugging of the program a copys created in the output folder - and then discarded when you stop the program.
This is not exactly a rare problem and a good indication of someone not using a search function to find a solution.

The specified table does not exist. [ table_Name] error

Hi all I have an small application to add the expense of the day.
For this I am using SQL compact database (CE). While inserting the record into a table name Expenses I am getting error
The specified table does not exist. [Expenses]
Insertion code is
using (var con =new SqlCeConnection(#"Data Source=|DataDirectory|\Database\Acadamy.sdf;
Persist Security Info=False"))
{
con.Open();
try
{
var Cmd = new SqlCeCommand();
String sqlAddNew = #"INSERT INTO Expenses (name, amount,receipt,details)
Values(#name,#amount,#receipt,#details)";
Cmd = new SqlCeCommand(sqlAddNew, con);
Cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtName.Text;
Cmd.Parameters.Add("#amount", SqlDbType.NVarChar).Value = txtAmount.Text;
Cmd.Parameters.AddWithValue("#receipt", SqlDbType.NVarChar).Value = txtRecept.Text;
Cmd.Parameters.AddWithValue("#details", SqlDbType.NVarChar).Value = txtDetails.Text;
Cmd.ExecuteNonQuery();
}
catch (Exception exception)
{
txtAmount.Text = exception.ToString();
}
finally
{
if (con.State == ConnectionState.Open) con.Close();
}
}
}
I am not getting why this error occurring.
Acadamy.sdf structure is as below:
I am able to retrieve data from another table of the same database. What will be the problem?
Whenever I get an error about a table that does not exist I use the SQL Server Management Studio and check if the table really is missing or if I just have a typo in my query.
Unfortunately the current version of the Management Studio no longer supports SQL Server Compact Database and you will have to use the 2008 version. You can get it directly from Microsoft: SQL Server 2008 R2 Management Studio Express

C# database writing to table doesn't work

I have a problem using Visual Studio 2010. I am using a service-based database (.mdf).
I have created a table manually in Visual Studio with some information. The code I have written can read from the table but when I insert new information it looks like the data is added to some other database.
I can read information from the correct table but when I add information to the table I can’t see the changes in Server Explorer in Visual Studio.
I don't know why to different databases are used! Does anybody know the problem?
Here is my code:
public class DataAccess
{
private SqlConnection sqlConnection;
private SqlCommand sqlCommand;
private SqlDataAdapter dataAdapterAnimal;
private DataSet dataset;
private string connectionString = DBAccessLayer.Properties.Settings.Default.AnimalDBConnectionString;
public DataSet LoadAnimalDataSet()
{
dataset = new DataSet();
using (sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
dataAdapterAnimal = new SqlDataAdapter("SELECT * FROM AnimalTable", sqlConnection);
dataAdapterAnimal.Fill(dataset, "AnimalTable");
sqlConnection.Close();
return dataset;
}
}
public void AddAnimal(int animalID, string name, double age, string category, string gender, string extraAnimalInfo)
{
sqlConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand("INSERT INTO AnimalTable VALUES(#AnimalID, #Name, #Age, #Category, #Gender, #ExtraAnimalInfo)", sqlConnection);
try
{
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("#AnimalID", animalID));
sqlCommand.Parameters.Add(new SqlParameter("#Name", name));
sqlCommand.Parameters.Add(new SqlParameter("#Age", age));
sqlCommand.Parameters.Add(new SqlParameter("#Category", category));
sqlCommand.Parameters.Add(new SqlParameter("#Gender", gender));
sqlCommand.Parameters.Add(new SqlParameter("#ExtraAnimalInfo", extraAnimalInfo));
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
catch (Exception ex)
{
throw;
}
}
I haven't seen your connection string yet - but from your description, it seems it might be this problem here:
the whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...

Categories