How to create database apps? - c#

How to create database apps?
I have a textbox, button and label. The user enters a value = Luke and the program does the Select Address From Customers where Name='Luke'. It displays Address in the label.
I know this is a pretty stupid question, but I've looked everywhere, and all I can find is how to display all columns instead of just one thing.
Anymore advice on databases with c# would be very help as well. I am using Sql server Express 2012 and Visual Studio
The Code:
private void button1_Click(object sender, EventArgs e)
{
SelectData(textBox1.Text);
}
private void SelectData(string selectConnection)
{
string connectionStr =
#"Data Source=.\SQLEXPRESS;"+
#"AttachDbFilename=C:\SQL Server 2000 Sample Databases\NORTHWND.MDF;"+
#"Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection connection = new SqlConnection(connectionStr);
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT Address FROM Customers"+
" WHERE CustomerName = '" + textBox1.Text + "'";

An advice for C# and Databases would be, to not put a string command together in the application.
There are many roads to success but some may lead to an unsecure Database query.
Personally I don't use, for example, the Entity Framework(Microsoft recommendation) etc. but I guess they might be helpfull for what you do so you should take a look at this.
Try to seperate the SQL Logic from the C# part so that IF your application grows and you can effort a Database administrator he doesn't have to know c# ;)

You are on the perfect track, now continuation to your code to display the address you can write like this:
label_address.text=command.executescalar();//if you have one row of address
else you can write
datareader dr =cmd.executereader()
while(dr.read())
{
label_address+=dr(0).tostring();+","//addressline1
label_address+=dr(1).tostring();//addressline2
}
hope its helpful

Related

Button not updating the database

I want to give the users to the ability to update their info on database. I made the button to for the software to take the name from one of the textboxes and send it to the database.
public void Updatebtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Update Users set First_Name=#fn WHERE ID = '2' ", con);
cmd.Parameters.AddWithValue("#fn", UFirstName.Text);
cmd.ExecuteNonQuery();
con.Close();
}
I watched a YouTube video and followed step by step. But it didn't work.
The button works and executes command. But something is wrong with either sql command or connection because the database doesn't get updated
because your codes seems okey to me with no problems in it i'll give you some tips that will make sure you almost avoiding most mistakes biggeners like me did which caused unexplaind errors.
these tips will REALLY REALLY help you in your programming journey.
when adding a new local database, create a newfolder and name it DataBaseFolder as an example inside your project folder , so you always know where is your database and you dont get confused about other databases in the default location VS saves them, and its better that the project folder is placed in the partition "C" in a default folder of windows.
when creating a new table, name it probably in the definition part at the bottom where you can see:
create table [dbo].[TableName] then press Ctrl + s, make sure to save that table in the same folder as your database, so you always know this table is for this project.
)))) each time you update your table definition like column name or type, or adding a new column or deleting an existing one, make sure to press Ctrl +s and save the table (replace) in the same folder you originally created it, that will make sure you don't get the error most new developers like me were stuck at which is the update window is taking forever to preview the changes.
))))) to make it easy for myself to use the sql commands, i created a script (class.cs) and put the important codes in methods with parameters so i save a lot of time when i was restarting over my program because of some mistakes i did :D
first i defined my sql connection in the class named SqlCodes:
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");
then i created my methods, examples:
public void QueryCommand(string QueryString)
{
con.Open();
SqlCommand cmd = new SqlCommand(QueryString, con);
cmd.ExecuteNonQuery();
con.Close();
}
public void FillingDataGridView(parameter1,parameter2, parameter3)
{
con.Open();
some code;
con.Close();
}
So, back to my main class where my button will function:
SqlCodes sqlCodes = new SqlCodes();
in the button i now can write:
sqlCodes.QueryCommand("insert into MyTable values (your values)");
or
sqlCodes.RefreshDataGridViewAfterEntry (parameter1,parameter2,parameter3)
or
string queryCommand = " insert into MyTable values (your values)";
sqlCodes.QueryCommand(queryCommand);
or in the load form method so when you open the program it shows the data you want instantly
{
sqlCodes.FillingDataGridview(parameter1,parameter2,parameter3)
}
if you're having errors with your database, don't delete the files you will find in the solution explorer because it will cause you some errors i couldn't figure their solution, just delete the database in the server explorer, and don't forget to change the sql connection path in the SqlCodes Class you created.
that will save you time and and to avoid errors and make your code very simple, instead of copy paste/ writing about 7 or 8 lines each time you want to do something with your database.
I managed to solve the problem.
As it Turns out. clicking the button also calls page_load. Which has a code that replaces text in the textbox. So the button would first call page_load. Retrieving data from the databox. Then it would put in the textbox.
Then it would take data from the same textbox again and send back it to the database.
I managed to fix it by putting the code in pageload inside in if statement. And then i put !Page.IsPostBack condition inside the if statement.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Active"] != null && Session["Active"].ToString()
=="Yes" && !Page.IsPostBack)
{
GetUserData();
}
}
Hope that helps.

how to talk to local databases?

I just added a new "local database" in my project using visual studio. Now I added the "New Data Source".
What I want to know is how you can do sql queries to the DB. I know how this is done in PHP but cant find good information about how to do this in C#. All I find is tutorials on how to drag detail or gridviews into the form.
I have one database called 'words' with three tables. I want to be able to do update queries to a row in each of these tables. something like this:
UPDATE easy SET words='blahblahblah' WHERE id=1;
How do you do this?
I am going to use SQL Server as example.
First you need to find out the connection string which should be similar to
_connectionString = "Data Source=(localdb)\\v11.0; Initial Catalog=words;Integrated Security=true;"
and then you do
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE easy SET words='blahblahblah' WHERE id=1;", connection))
{
cmd.ExecuteNonQuery();
}
}

C# SQL Database Windows Form Login System

Im working on a SQL database project in C#. I'm looking to create a login form which will be presented when someone starts the application.
The connection is made to the database, however they must enter a correct username and password into the first form before they can proceed to see the rest.
I have created 2 text boxes, and a button txtusername and txtpassword and a button login.
Here is my SQL command:
SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE Username ='" + txtUsername + "' AND Password = '" + txtPassword + "'", Program.cs);
I'm looking for a way to show in a label if the sql command yields a result meaning the username and password is stored in the user table then it returns true or something. If there is a more efficient or effective way to this also let me know :).
You should never create command texts by concatenating strings. Use SqlParameter. That is to put first things first.
And it seems to me that you have no (or very little) understanding how data access works in .net. So I'd recommend you to read some books on that topic, for example, Microsoft's "Accessing Data with .NET Framework 4".
This code is a Vulnerability in your project
See this for details
strong text*code for login page
b
tn_click() //button click event
{
Sqlconnection con=new
sqlconnection(Strcon);
String sqlquery="select usrname,password from loginpage where username='textname.text' and password='textpassword.text'";
Sqlcommand sqlcom=new Sqlcommand(Sqlquery,con);
con.open();
Sqldatareader dr;
dr=sqlcomm.executereader(commandbehavior close connection);
if(dr.read())
{
session["un"]=dr["username"].Tostring();
session["pwd"]=dr["userpassword"].Tostring();
if(dr["userpassword"].Tostring()!=null);
respone.redirect("userdetail.aspx");
}
else
{
respone.redirect("login.aspx");
}
else
{
lblmsg.text="invalid user";
}
}

SQL Server Express inserts doesn't work anymore

In my C# application, I do the following:
using (SqlConnection connection = new SqlConnection(connectionstr))
{
connection.Open();
SqlCommand com1 = new SqlCommand("insert into Anfangstierbestand(bestand, jahr, loginid) VALUES (" + bestand + ", " + jahr + ", " + loginid + ");", connection);
SqlCommand com2 = new SqlCommand("select * from Anfangstierbestand;", connection);
com1.Connection = connection;
int ferksum = 0;
com1.ExecuteNonQuery();
connection.Close();
connection.Open();
SqlDataReader read = com2.ExecuteReader();
while (read.Read())
{
ferksum += Convert.ToInt32(read[2]);
}
// MessageBox.Show("Fehler beim Erstellen des Tierbestandes", "Fehler"); }
MessageBox.Show(ferksum.ToString());
}
It's a simple insert to a database. I added com2 to check, if the insert works.
Unfortunately, the the value of com2 tells me, that it works, but when I go to the Server Explorer and press Execute SQL, there are no new values.
I don´t know the reason. The code above is just an example, since a few days, no insert works anymore(before, the same code works).
Does anybody know what the reason can be?
EDIT:
C#:
string connectionstr = "Data Source=.\\SQLEXPRESS;" + "AttachDbFilename=|DataDirectory|\\Datenbank\\FarmersCalc.mdf;" + "Integrated Security=True;" + "User Instance=true;";
EDIT2:
Server Explorer:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\user\Desktop\Farmer´s Calc\Programmierung\WPF\Finanz_WPF\Finanz_WPF\Datenbank\FarmersCalc.mdf";Integrated Security=True;User Instance=True
EDIT3:
Here are the columns:
id int,
jahr int,
anzahl int,
loginid int
EDIT4:
Is it possible that it´s a problem that I opened my project with expression blend? Normally, I work with VS 2010...
EDIT5:
Even because I can not answer my question(<100 reputations) I write it here:
Shame on me. Some of you were right, it was the wrong database-file. But I´m still wondering, why this happened, because I did not change anything since a few days and before this, it worked!
Thanks to all for helping!
You're using user instances, why? Isn't it possible that the instance you're connecting to in Server Explorer is not the same as the instance where your app is inserting data? What happens when you select data from within the app, does it reflect your insert(s)? It seems to me based on your connection strings that these are two completely different MDF files - they have the same name but they are in different locations.
Is the issue implicit transactions? Do you need to issue a commit of the SQL Insert? If com2 tells you that it's there then it may only see it since it's in the context of the current SQL transaction.
You should share your connection string for both Server Explorer and your SqlConnection (connectionstr). Ensure that you setup your Server Explorer connection with User Instance=true;.
As a diagnostic,
connection.Open();
int n = com1.ExecuteNonQuery();
// log or show 'n' , the nr of rows affected
Edit, after seeing the connectionstrings:
local db files in |DataDirectory|\ are very prone to be overwritten by the next run or build command.
Make sure you set them to 'copy never' or 'copy if newer' in the VS Solution explorer.
Perhaps somewhere in the callstack above this code, someone has added a TransactionScope.
This would cause the connections to enroll automatically in the transaction, and the connections could see the data inserted via that not-yet-committed transaction. When the scope is exitted without calling scope.Complete, the transaction gets rolled back and no data is saved.

SQL Server database doesn't delete records

I have a SQL Server database in a C# project.
I use a connection string to connect to it.. I can use the method ExecuteNonQuery to insert data, no problem there.
But when I delete, it only deletes it momentarily, as soon as I restart the application it kind of rolls back the deletion.. Any ideas?
PS: I tested the string in a direct query, and it worked fine there.
public void executeNonQuery(string input)
{
db.Open();
SqlCommand cmd = new SqlCommand(input, db);
cmd.ExecuteNonQuery();
db.Close();
}
EDIT: DELETION CODE:
private void buttonSletPost_Click(object sender, EventArgs e)
{
if(dataGridView1.GetCellCount(DataGridViewElementStates.Selected)>0){
for (int i = 0;i < dataGridView1.GetCellCount(DataGridViewElementStates.Selected); i++)
{
String str1 = String.Format("WARNING about to DELETE:\n {0} \n BE CAREFULL NO TURNING BACK NOW!", Regnskab.getInstance().dbSelectPostID(dataGridView1.SelectedCells[i].Value.ToString())[0].ToString());
if (MessageBox.Show(str1, "Confirm Deletion", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string str = String.Format("DELETE FROM PostTable WHERE PostID={0}", dataGridView1.SelectedCells[i].Value.ToString());
Database.getInstance().executeNonQuery(str);
Console.WriteLine(str);
}
}
}else {MessageBox.Show("No cells selected");}
}
Which will give following output:
DELETE FROM PostTable WHERE PostID=7
Connection string in app.config:
<connectionStrings>
<add name="EndProject.Properties.Settings.DBtestConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DBtest.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" providerName="System.Data.SqlClient" />
private Database()
{
string connStr = ConfigurationManager.ConnectionStrings["EndProject.Properties.Settings.DBtestConnectionString"].ConnectionString;
db = new SqlConnection(connStr);
}
And then I open and close it, so the connection ain't open each time.
To be honest:
I don't exactly know where to see my DB info, here's some info from properties in VS2010.
Provider: .NET Framework Data Provider for SQL Server
Type: Microsoft SQL Server
Andrew's 3rd: I think they are deleted momentarily because I reloaded the information in my datagridview and from there it is gone. But then when I close the application and start it again, it is back...
Also i just checked with VS2010's server explorer and did a "Show Data" after I deleted (before I shut it down) and it wasn't deleted.
But I'm totally clueless now. :-(
Many applications use Transactions to manage db connections. SQL Server doesn't do it by default, but other factors in your application may be doing this.
Also, if you're really doing this, and your input is coming from a user interface, I can't wait to introduce you to Little Bobby Tables
Use the SQL Server Profiler to run a trace and capture the actual T-SQL statements that are getting executed on the database.
This is the easiest solution.
The behavior you're describing sounds like autocommit is off. Try the following and see if the record(s) stays deleted:
public void executeNonQuery(string input)
{
db.Open();
using (var txn = db.BeginTransaction())
{
SqlCommand cmd = new SqlCommand(input, db);
cmd.Transaction = txn;
cmd.ExecuteNonQuery();
db.Close();
txn.Commit();
}
}
Ok it was apperently me who was mistaken on the inserting part...
Someone suggested that i was because of the Visual Studio databases created every time the applikation ran.
So i installed MS SQL 2008 R2. Created a new DB with same layout.
Changed the connection string
And wuupti woo it seems to work, ill come back to this thread if it breaks down later..
But delete + insert both working greatly now :-)
Thanks to all who tried to help!

Categories

Resources