HomeОбразованиеRelated VideosMore From: ProgrammingKnowledge

C# Tutorial 6: Insert/Save data to database

686 ratings | 351041 views
------------------Online Courses to learn---------------------------- Java - https://bit.ly/2H6wqXk C++ - https://bit.ly/2q8VWl1 AngularJS - https://bit.ly/2qebsLu Python - https://bit.ly/2Eq0VSt C- https://bit.ly/2HfZ6L8 Android - https://bit.ly/2qaRSAS Linux - https://bit.ly/2IwOuqz AWS Certified Solutions Architect - https://bit.ly/2JrGoAF Modern React with Redux - https://bit.ly/2H6wDtA MySQL - https://bit.ly/2qcF63Z ----------------------Follow--------------------------------------------- My Website - http://www.codebind.com My Blog - https://goo.gl/Nd2pFn My Facebook Page - https://goo.gl/eLp2cQ Google+ - https://goo.gl/lvC5FX Twitter - https://twitter.com/ProgrammingKnow Pinterest - https://goo.gl/kCInUp Text Case Converter - https://goo.gl/pVpcwL -------------------------Stuff I use to make videos ------------------- Stuff I use to make videos Windows notebook – http://amzn.to/2zcXPyF Apple MacBook Pro – http://amzn.to/2BTJBZ7 Ubuntu notebook - https://amzn.to/2GE4giY Desktop - http://amzn.to/2zct252 Microphone – http://amzn.to/2zcYbW1 notebook mouse – http://amzn.to/2BVs4Q3 ------------------Facebook Links ---------------------------------------- http://fb.me/ProgrammingKnowledgeLearning/ http://fb.me/AndroidTutorialsForBeginners http://fb.me/Programmingknowledge http://fb.me/CppProgrammingLanguage http://fb.me/JavaTutorialsAndCode http://fb.me/SQLiteTutorial http://fb.me/UbuntuLinuxTutorials http://fb.me/EasyOnlineConverter -------------------------------------------------------------------------------- How to: Insert New Records into a Database Database Access with Visual C#.NET sql server - Insert Data into database in C# How to insert Data to Ms SQL server 2008 using C#.net .net - C# insert data into SQL table Using Visual C# and SQL cannot insert data into table..‎ c# import data from text file into sql databse line by line‎ store xml in SQL Server 2008 from C#‎ Using SQL in C# - Cannot insert data into SQL table visual C# - Could not Insert the data using VC# in MYSQl Add, save & retrieve data in SQL insert data in sql 2005 from excel file through c# asp.net‎ insert data into SQL table from pre filled boxes in C# 4.0‎ insert into database unsing ado.net and C#‎ Insert DateTime into SQL Server using C#‎ Searches related to c# insert data into sql c# insert data into sql table c# insert data into sql server inserting data into sql table insert query sql insert statement from another table
Html code for embedding videos on your blog
Text Comments (164)
Jordan Ponder (26 days ago)
@9:42 I only have, available to me, 'using System.Data.SqlClient;'. Will I be able to achieve the same effect, even though I will have to use tools within 'Systems' rather than 'MySql' to interact with the database I created? ex. I have to use " 'SqlConnection' conDataBase=new SqlConnector(constring); " rather than, the demonstrated: " 'MySqlCommand' cmdDataBase = new MySqlCommand(..etc " Does anybody know if it'll mean anything significantly different in 2017 Visual Studio?
jailbirdx0x (2 months ago)
Why is it that even when a value is an integer, you add the '"+Textbox.Text+"' value? Isn't that for strings?
Sanju Ponugumati Teja (2 months ago)
Where did u close the connection?
Cherlyn Micarandayo (4 months ago)
Those were very useful for a student like me sir :).. Thank you very much! By the way, can you make a video on uploading large files to database sir? I'm currently creating a system that must store large files and I don't know how. Can you please help me? It will be very appreciated.
Benjamin Musasizi (4 months ago)
How the heck one gives a thumbs down to these useful and informative videos is totally beyond my comprehension. Thanks alot
sebedeus nghinanye (5 months ago)
evening where can I find the videos before this one, I want to follow from the start pls.
Aadil Sayed (5 months ago)
Question :- if the save button is pressed two times it gives an error then how to check if the data is duplicate or not???
Ziffi HaiQal (6 months ago)
x1.5 speed might help. great video bytheway.
oaks sinatra (7 months ago)
Speed 1.5
Domagoj Hamzić (8 months ago)
You dont need to insert ID of employees, it is not user friendly. Just check AI (Auto Incremental) box for employeID in your database :)
Melvene Diaz (3 months ago)
not all the time
grace amegboh (8 months ago)
thank you! you are the best!
Real_na Jr (8 months ago)
Hey I'm new to programming so I need some help understanding. Is there any way I can create an application similar to this (without the login window), by using an array instead of a database? Thank you!!
Ani (8 months ago)
Thank you
Marko Fabijan Pavlović (9 months ago)
What if I have .mdf file instead of .db3 file?
Firdous Cheriya Vadappil (9 months ago)
I used the same code for inserting data but it doesnt get reflected in tha database And also i have used sqlserverce and not sqlclient What to be done in to insert data inthe database and also it must be reflected their
Jason Yousef (9 months ago)
very poor way, hope nobody is following that crap!
Muhammad Usama Zuberi (10 months ago)
You'll definitely find it useful. Here I have shown that how to use INSERT, UPDATE, DELETE & SELECT commands of DML in C# using MS Access. Link is: https://www.youtube.com/playlist?list=PLUDBhhQ1e0K7PoZCOLdvqjuxpo1BX2JGQ Well, I'm also gonna add some more videos very soon.
Nishan Harshana (1 year ago)
Thank you for helping us
Muhammad Nabeel (1 year ago)
kindly send me the link of the playlist
Juan Siu (1 year ago)
piece of shit video
Syed Salman nadeem (1 year ago)
https://youtu.be/rwiUxba6kQM
שלו אלקיים (1 year ago)
Thank you
Chathura Rathnayake (1 year ago)
can i download your this sample program
word press (1 year ago)
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.' why this probelm showed up again and again?
rafat ali (1 year ago)
tutorial#6? where is 1,2,3,4&5 ? i couldnt find ? please help.
Jason Tsimplis (1 year ago)
STOP MOVING THE FREAKING MOUSE CURSOR AROUND IN CIRCLES !! FOR THE LOVE OF GOD... WE__CAN__SEE__THE__MOUSE__CURSOR!!
binod kumar Rana (8 months ago)
Go to properties and change mouse cursor
Ahmad Sheikh (1 year ago)
Sir Please also tell how to insert save update delete connecting Microsoft Access
Rana Arsalan Javaid (1 year ago)
good.
Hamza Asad (1 year ago)
it is giving error in my query ?
Timy Jose (2 years ago)
how to remove avoid system.windows.forms.textbox from database (which is entered to sql database automatically using this programme)
Wajid Ali (2 years ago)
Thanks sir it is really helpful. I follow your tutorials for every language e.g java android, c# and many more...Thanks sir for such a creative mind and ideas...Really fan of you.
Infamous User (2 years ago)
but what if you wanted to search a certain value then change it? like you wanted to update that value programmatically?
Everlovingful (2 years ago)
Omg Dude thank you so much! Learning programmatic editing of a database has been a hell for me so far as no tutorial about Dataadapters worked. I actually could use dataadapters only for reading data instead of editing. And now I found your tutorial which showed completely different approach to creation of SQL commands (through DataReader) and running them in C#. WHy does this shit have to be so complicated=(
GrandAlchemist (2 years ago)
new to databases and sql... is all this " '+dsafds+" ' , " '+adsdj+'"; , ; stuff normal? Like, is this common practice? seems hard to remember.
tadpole281 (2 years ago)
Normally in sql you would only use a single quote( ' ' ). However since its being used in c#, in order to use c# commands within the sql code you have to add the double quotes (" "). The double quotes allows the computer to know you are using c# code instead of sql.
Jimmy Lee (2 years ago)
If i create this and convert it into an installable program will i have to set the database up on a new computer or will the one i create go with it in the installer package. i will only have about 100 or so users stored into it
Jun Lee Martel (2 years ago)
can you also have tutorial on How To Search Values From MySQL Database And Set It Into TextBox?
iWaxflax (2 years ago)
How do i save it to Access?
ANAMAX CSGO (2 years ago)
How 190 000 peoples can watch this and doing it ^^
Anizaga (2 years ago)
Wow. Thank you very much. This has helped me a lot :)
Ammad Raza (2 years ago)
i want to connect visual studio with SQL by using a class so that i can invoke my connection class to my whole project. is your any tutorial which could help me?
Domagoj Hamzić (8 months ago)
ADD New Item/ Class/ Cut Connection Code from Form1 and paste it in created Class / Create Object of class in Form1 and call your connection in class with constructor or method in class... CreatedClassName objectName=new CreatedClassName(); in Created Class make Constructor... public CreatedClassName(){connection code...}
Bilal Khan (2 years ago)
guys! how to download the entire tutorial simultaneously...
Mohammed Khadir (2 years ago)
copy url example take the below one https://www.youtube.com/watch?v=sSBx9_eddmo&list=PLS1QulWo1RIZrmdggzEKbhnfvCMHtT-sA&index=5 paste it in you-tube down-loader it will ask you whether you want download the whole play list or single if whole playlist then click yes or you click no ok
Putra Wahyu S (2 years ago)
Data not saved into database (MySQL) but it says "Saved". please help :(
ScrappyHaxor (2 years ago)
Thank you <3 1+ sub
158lucky (2 years ago)
I'm using sqlclient insead of mysql i'm getting an error of "IDENTITY_INSET IS SET TO OFF" can you please help me
Praveen HARAN (2 years ago)
+158lucky how about checking your Identity Specification in sql
Beggi Swag (2 years ago)
Will this work for example if someone uses my program in another computer will I get It in my database?
faseel khan (2 years ago)
How to insert into one to many relationship? pls help me
FlipFuL Beatbox (3 years ago)
11:48 can you explain about what does this while loop do? (you didn't explain in this video) and why you don't have any close sqlconnection and close sqlreader ? thanks.
Domagoj Hamzić (8 months ago)
your code will work without this while loop...
Firdous Cheriya Vadappil (9 months ago)
FlipFuL Beatbox Even i wanna know
Mystery Guy (3 years ago)
Beware. This SQL Database has only 2 gigabyte. if you have 100,000 users in your website will have a big error. I use redis database because it can give me INFINITY Gigabyte.
Witzbold1983 (3 years ago)
How can i do that my DataGridView refresh after Save?
kim lapitan (3 years ago)
pls help. when i click the save button it always shows "unknown command".heres my code { string constring = "Server=localhost;port=3306;username=root;password=;"; string Query = " insert into classical.liszt (USERLEVEL) value('" + this.textBox3.Text+"');"; MySqlConnection conDataBase = new MySqlConnection(constring); MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase); MySqlDataReader myReader; try { conDataBase.Open(); myReader = cmdDataBase.ExecuteReader(); MessageBox.Show("SUCCESSFULLY CHANGED"); while (myReader.Read()) { } } catch (Exception k) { MessageBox.Show(k.Message); } }
Praveen HARAN (2 years ago)
+kim lapitan change value to VALUES
ayoub jebli (3 years ago)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' values () at line 1 what should I do?
Balthier Sky (3 years ago)
what code for if the username is already taken message box show error(username is already in use) and data will be not save please help ASAP
Amy Le (3 years ago)
if my server is MSSQL server, how do I create the SQL Server connection?
Amy Le (3 years ago)
Thanks Fernando
Fernando Telles (3 years ago)
+Amy Le You gotta use using System.Data.SqlClient; and then SqlConnection, SqlCommand and so on...
Beatrix Ducz (3 years ago)
Hi, Where is the query designer that used to be there?
Ziaul Zia (3 years ago)
Why is the while loop empty? Can someone give me any explanation?
Marta Costa (3 years ago)
Error: The name 'value' does not exist in the current text. Why is this happening? :/
Teraprinny (3 years ago)
You should really also show your viewers that using parameters is a most safe way to avoid SQL injections. Either way, thanks for the tut!
MParwez K (3 years ago)
These codes does not take into consideration empty textboxes. Please make a video on this purpose.
Dimon12321 (5 months ago)
Like that: ...(code above) MySqlReader myReader; if (username_txt.Text == "" || password_txt.Text == "") { MessageBox.Show ("One of your fields is empty. Fill it and press (button name) again!"); } else { try { myConn.Open (); ...(code below)
TheMaad (3 years ago)
+MParwez K You can check if they are empty with simple IF, before executing MySQL query.
Muhammad Hakimmi (3 years ago)
delegate to an instance method cannot why this can happend
Alex Jabz Evans (3 years ago)
keep getting pop up message saying 'Field user_name doesn't have a default value' even though I'm not wanting to add data to that column in my database! Can anyone help?
Yusuf Bülbül (3 years ago)
 But, I take this error: "you have an error in your sql syntax check the manual that corresponds to your mysql server version for right syntax to use near.... bla bla.."  does someone know to solve this problem? 
Yusuf Bülbül (3 years ago)
+Valko Valkov  thanks for answer.  I solved the problem. Instead of   database.edata,     I wrote  'database'.'edata'  and problem was solved. 
Valko Valkov (3 years ago)
...I had the same problem.   Sure you use MySQL key phrases (from, where...) in column names of tables. Check the names of the variables.
26matthew1 (3 years ago)
Help please. My program ran but when I press the create account button, it did not prompt the success msg box, but instead it says "incorrect syntax near the keyword 'database'. ".
Ultramate Gaming (3 years ago)
thanks for your help!!!
J u (3 years ago)
I love your voice ,  it helps me a lot xd
Kieran Green (3 years ago)
why is the while loop empty? wouldn't it be better to put some rules in to say if you are trying to input a duplicate etc?
FlipFuL Beatbox (3 years ago)
+Kieran Green i got the same question and i dont know why
the only problem i am facing here is the messageBox.Show() method...Any ideas how to implement popup windows in Visual Web Developer 2010?
Kieran Green (3 years ago)
messageBox.ShowDialog()
Ronald Johnson (3 years ago)
Thank you.
yan kumar (4 years ago)
thanks for sharing ProgrammingKnowledge
Umit E. (4 years ago)
appreciate your effort but i have to say that you are so boring! and first 5 mins of the video is useless bulshit.
Umit E. (2 years ago)
+Arun Pillai First I appreciated his work, second I let you see the positive side by informing not to watch first 5 mins! ;)
Arun Pillai (2 years ago)
+Umit E. why dont u appreciate some one's work......... let us see the positive side..
Lahiru Rathnaweera (4 years ago)
this is really good effort!
I-hate-Google (4 years ago)
is it possible to automatically increment the Eid? so you don't have to remember the last one in DB and remember to write the next it in your app?
Odilbek Saporov (3 years ago)
+I-hate-Google try when you creating TABLE Auto Increment
JonnyB (3 years ago)
+MD. Mahmudul Hassan Farazi Maybe replace the code that remembers with code that sets the EId to a value that isnt present. Or increment everytime that an error occurs while creating the data column
+Edmond Caseñas How??
thanks!!!
jaime cruz (4 years ago)
holy crap thanks for this tuto .the only problem i had on mine was the line  "constring= ... " my source was Data Source=JAIME;Initial Catalog=DataBase2;Integrated Security=True  and in Query i just put the name of the table only and it runs and saves into my database 
Slinky (4 years ago)
I get an error when doing this saying "Unable to connect to any of the specified MySql Hosts"
Ashok Kumar (4 years ago)
thank you..
MrMOABKING1313 (4 years ago)
can u do this whole tutorial on vb.net not C# or C++
BlackRa1n (4 years ago)
Hello, i need your help. I just coded a ping pong game with scores etc. The score & the username & the password is on my SQL server. How can i read my score in my form? For example: I'm Peter and my highscore is 29. SQL: nickname: peter highscore: 29 I want the following: A button in my form (Show highscore). When I press the button, the following should appear: Nickname: Peter Highscore: 29
guetty abboud (4 years ago)
i used your code in video 11 to create combobox. and now m triying to save the informations but it's always giving me an error . anyone can help me ? this is the program :   string Connstring = " datasource = localhost; port = 3306; username = root; password = 3306";             string Querry = " insert into database.courses (crs#, name , credits , grade) values('" +this.textBox2.Text + "' '" + this.textBox1.Text + "' , '" + this.textBox6.Text + "' , '" + this.textBox11.Text + "') ;";             MySqlConnection ConnDataBase = new MySqlConnection(Connstring);             MySqlCommand CmdDataBase = new MySqlCommand(Querry, ConnDataBase);             MySqlDataReader myReader;                 ConnDataBase.Open();                 myReader = CmdDataBase.ExecuteReader();                 MessageBox.Show(" Information Is Saved");                 while (myReader.Read()){} The crse column is a combobox in the form2. what i want to do is add a new course, naming it and its credits and grades
Alberto chapa (4 years ago)
you should use cmdDataBase.ExecuteNonQuery()  instead of ExecuteReader(), because you are not going to retrieve any data, just update it
Tomasz M. (4 years ago)
You are to slow MEN!!! In many videos you said the same information few times. Your tutorials are valuable, but veeeeeery slow (sametimes annoying)...:/
Ayman Elsayed (4 years ago)
+ProgrammingKnowledge it show's me this weird message (unknown column" " in field  
a aln (4 years ago)
hello, i tried your codes and i got this error (The method or operation is not implemented) , i'm sure i wrote the codes right >.< ,i would like know why ?. thx
Mukesh Vishwakarma (4 years ago)
You have already explain about database connection in 1 Tutorial.
Imanos Imanoss (4 years ago)
Thank u soooooooooooooooo much for your videos!!!!!! They are great and sooo precise!! God bless u!
wilyoustay (4 years ago)
man great videos working fine . Could you make a video where we can use dataconnection in c# to connect mysql tables u just made to c#? thanks
Alex Charlton (4 years ago)
Hello, I've used the code you provided, but get 2 errors, one of which says: "cannot convert from 'string' to 'mysql.data.mysqlclient.mysqlconnection" I Was wondering if anyone knows how to fix it? It seems to be pointing to this line of code: MySqlCommand cmdDatabase = new MySqlCommand(sQuery, connStr); Here is my query also, just incase that is needed: String sQuery = "INSERT INTO database.scoreboard (PlayerName, Score) VALUES('" + this.lblX_Win_Count.Text + "', '" + this.lblX_Counter.Text + "');";
Alex Charlton (3 years ago)
+kim lapitan Hi Kim, Not sure if this will make much different, but I noticed some of your code is lowercase, For example insert should usually be entered as INSERT. Mostly on your actual query itself, so it may be worth updating this line: string Query = " insert into classical.liszt (USERLEVEL) value('" + this.textBox3.Text+"');"; to the following: string Query = "INSERT INTO classical.liszt (USERLEVEL) VALUE('" + this.textBox3.Text+"');"; Other than that, I can't really see any problems with your syntax, have you tested that you are actually connected to the MySQL Database before running this query?
kim lapitan (3 years ago)
+maike Mota hi can you help me. when i hit the save button it always says unknown command... anyway heres my code.{ string constring = "Server=localhost;port=3306;username=root;password=;"; string Query = " insert into classical.liszt (USERLEVEL) value('" + this.textBox3.Text+"');"; MySqlConnection conDataBase = new MySqlConnection(constring); MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase); MySqlDataReader myReader; try { conDataBase.Open(); myReader = cmdDataBase.ExecuteReader(); MessageBox.Show("SUCCESSFULLY CHANGED"); while (myReader.Read()) { } } catch (Exception k) { MessageBox.Show(k.Message); } }
maike Mota (4 years ago)
:)
Alex Charlton (4 years ago)
+maike Mota Hello, Thanks for your reply, I've managed to sort the code now anyway :). Thanks a lot though ^_^
maike Mota (4 years ago)
And in here: MySqlCommand cmdDatabase = new MySqlCommand(sQuery, connStr); change the connStr for your object that is constructed with the MySqlConnection() method. You just use the connStr in the MySqlConnection() contructor. EX: try{ MySqlConnection myConn = new MySqlConnection(connStr); myConn.Open() String sQuery = "INSERT INTO database.scoreboard (PlayerName, Score) VALUE('" + this.lblX_Win_Count.Text + "', '" + this.lblX_Counter.Text + "');";  MySqlCommand cmdDatabase = new MySqlCommand(sQuery, myConn); If(cmd.Database.ExecuteNonQuery()>0) {     MessageBox.Show("SAVED!"); } else {    MessageBox.Show("OPS, SOMETHING HAPPENED WITH YOUR CONNECTION"); } myConn.Close(); }catch(Exception ex) {    MessageBox.Show(ex.Message); }
Sergey Roadstar (4 years ago)
thanks for the video!
Karen Kearns (4 years ago)
the jittery mouse  throughout and shifting screen especially at the start was very distracting but otherwise very good and easy to understand thanks
CodeMonkey (4 years ago)
Can you just please stop moving your cursor? 
AgentSpamCorp (1 year ago)
For me that I haven't sound, his mouse movements helped me.
jenan savanath (4 years ago)
hi, I followed the the code and uses my own db server and password, however when I click the button save, the application freezes and the database is not updated...there are no errors in the code, I don't know whats wrong with it. Can you please help?
Frank Tamen (4 years ago)
What would it look like if i wanted to use a autoincrement in order to gain automatic user-ID for example? :)
Gether Medel (4 years ago)
string commandString = "SELECT * from "your table";             OleDbDataAdapter dataAdapter = new                            OleDbDataAdapter(commandString, "your connection string");             DataSet ds = new DataSet();             dataAdapter.Fill(ds, "Any NAME");             int dataTable = ds.Tables["Any NAME"];             int currRec = 0;             int totalRec = dataTable.Rows.Count; then just use this - Convert.toString(totalRec); and put it in your Id VALUE like EXAMPLE INSERT INTO "your table" (Id, Name) VALUES(' " +Convert.toString(totalRec)+ ' ", ' " +Mike+ " ') Copy this first. just try to understand it:)
Gaston Baladi (4 years ago)
You are slow.... But you are GOLD and GOOD.
Indians Life (4 years ago)
very nice..and useful
Eyal Noked (4 years ago)
the mouse constant move made me nauseous
floyd harrison (1 year ago)
that is your reply lol
AgentSpamCorp (1 year ago)
For me that I haven't sound, his mouse movements helped me.
Marky Mark (5 years ago)
When I am pressing "Save" it just says "Waiting for localhost" and never culminates... Why?
Abdirahman Moahamed (7 months ago)
SaSinKaL connect your computer to the sql server
Linked (5 years ago)
Hello brother, i have your complete tutorial of java, and for that java tutorial you numbered everyone but this one for c#  i can't find the the starting point! 
Duwa (5 years ago)
database = DAAATABIS
link9367 (5 years ago)
I speak spanish, and this sounds really weird even for someone who's got no so much practice, i'd say he's not spanish , i think he's from india (dunno how you say it in english), hahaha
Kamilo Guiral (5 years ago)
hispanish
Yanky Kalifornia (5 years ago)
great video

Would you like to comment?

Join YouTube for a free account, or sign in if you are already a member.