How to add data into MSQL database by using c# programming? - c#

Good day!
Using visual studio 2012, I have created a Student class with get and set codes, and i need to complete the StudentDAO class to create insert coding that will use to store data to database student table. this action is perform by a windows form button click event.
what i need to create a button click code and then insert into database code,
//Student.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SRSJason
{
class Student
{
private string S_Student_id;
private string S_Full_name;
private DateTime S_Dob;
private string S_Address;
private int S_Contact;
private string S_Username;
private string S_Password;
public Student() //Default constructor
{
}
public Student(string Student_id, string Full_name, DateTime Dob, string Address, int Contact, string Username, string Password) //Overloadign
{
S_Student_id = Student_id;
S_Full_name = Full_name;
S_Dob = Dob;
S_Address = Address;
S_Contact = Contact;
S_Username = Username;
S_Password = Password;
}
public void setID(string Student_id)
{
S_Student_id = Student_id;
}
public string getID()
{
return S_Student_id;
}
public void setName(string Full_name)
{
S_Full_name = Full_name;
}
public string getName()
{
return S_Full_name;
}
public void setDob(DateTime Dob)
{
S_Dob = Dob;
}
public DateTime getDob()
{
return S_Dob;
}
public void setAddress(string Address)
{
S_Address = Address;
}
public string getAddress()
{
return S_Address;
}
public void setContact(int Contact)
{
S_Contact = Contact;
}
public int getContact()
{
return S_Contact;
}
public void setUsername(string Username)
{
S_Username = Username;
}
public string getUsername()
{
return S_Username;
}
public void setPassword(string Password)
{
S_Password = Password;
}
public string getPassword()
{
return S_Password;
}
}
}`
//StudentDAO class (please help me to complete this code)
`class StudentDAO
{
static string constring = "Data Source=JAZE;Initial Catalog=srsjason;Integrated Security=True";
SqlConnection m_con = new SqlConnection(constring);
}`
//button click from the form (please help me to complete this code as well)
private void submitstudent(object sender, EventArgs e)
{
}
please help me to complete this coding

First of all when you create private properties u cant access them in your forms, you have to create a method instead inside the same class then use it in your form. second you should know about the ORM - Object Relational Mapping that you are using.
Here I'll list them:
ADO.NET
LINQ to SQL
ADO.NET Entity Framework
When you picked one of those. next step would be learning about how they work and whats the syntax.
However knowing that you kinda showed a syntax of ADO.NET Here is an Example how you can insert the data in your data base using ADO.NET. If you want to add data directly from code-behind without a method. so basically on click event of your button.
private void btn_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
//Execute command by calling following method................
//1.ExecuteNonQuery()
//This is used for insert,delete,update command...........
//2.ExecuteScalar()
//This returns a single value .........(used only for select command)
//3.ExecuteReader()
//Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
Be sure that you've included your ConnectionString in your config file.

Related

Saving Images to Mysql Database as Blob- Xamarin

I want to save images into my mysql database.
This is my code:
The class:
public async void SIE()
{
TrialClass trialClass = new TrialClass(ImagesPaths1);
BlogRestClient<TrialClass> restClient = new BlogRestClient<TrialClass>();
await restClient.PostAsync(trialClass);
}
public class TrialClass
{
public List<ImageFormatClass> ImagesPath2;
public TrialClass(List<ImageFormatClass> imagespath)
{
ImagesPath2 = imagespath;
}
}
public class ImageFormatClass
{
public Image SavedImage;
public int Format;
public ImageFormatClass()
{
}
}
private void Post_Clicked(object sender, EventArgs e)
{
SIE();
}
Web API controller:
public void Post([FromBody] TrialClass value)
{
foreach (ImageFormatClass s in value.ImagesPath2)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.blogimagestable (ImagesId)values( ?str);";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.Parameters.Add("?str", MySqlDbType.VarString, 256).Value = s.SavedImage;
cmd.ExecuteReader();
conn.Close();
}
}
Anytime I press the post button to fire the Post_Clicked event, I get this error
Newtonsoft.Json.JsonSerializationException: 'Self referencing loop detected for property 'ManifestModule' with type 'System.Reflection.RuntimeModule'. Path 'ImagesPath2[0].SavedImage.Source.Stream.Method.Module.Assembly'.'
at `await restClient.PostAsync(trialClass);

Passing textbox value to a function

I am having a problem with my login application. I am trying to get user type from the database based on username. When I pass the name from textbox user type will be null. Otherwise, when I declare the name manually it will work and gives the user type!!!
This is my code:
public string usertype { get { return label3.Text; } set { label3.Text = value; } }
public string username { get { return txtname.Text; } set { txtname.Text = value; } }
private void Login_Load(object sender, EventArgs e)
{
username=txtname.Text;
label3.Text=Users(username);
}
public string Users(string name)
{
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stock;Integrated Security=True"))
{
string sql = "SELECT usertype FROM[dbo].[LoginTable] where UserName =#UserName";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#UserName", name);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
usertype = reader["usertype"].ToString();
}
con.Close();
}
}
return usertype;
}
//Main form to access user type for security
Login login = new Login();
string type=login.usertype; //-----usertype null
Note that I am accessing user type from user_control in the main form, don't know if it differs.
It works by changing the function location to the txtname_TextChanged event. Thanks all

Update Collection Value with Database in UWP(MVVM)

I have custom collection which contains student_id,student_name,student_mark.And having the table with same columns in the database as well. The design form have some controls for updating the existing student.
Temporarily all the updating operations are done with that custom collection.Lets assume we have 100 students data in collection and database. Any updating operation should reflect in the collection. But what my doubt is how do i update these values with the database before i close the application??
But when i open the application the collection should have all the values which have stored in the database.
But what my doubt is how do i update these values with the database
Firstly, you need to know how to do CRUD operations on MySQL database with uwp app. For this, please reference this sample.
Secondly, according to your description, you have built up a MVVM project to bind a collection data to the view. But you didn't have a data layer for this MVVM structure. For this, you need to create a class for data layer to do GRUD operations, and establish contact with this data service from ViewModel. More details please reference this article.
The class for data layer I wrote according to your description which contains how to read, update and delete data from mysql database is as follows:
public class Student
{
public int Student_id { get; set; }
public string Student_name { get; set; }
public string Student_mark { get; set; }
}
public class DataService
{
static string connectionString;
public static String Name = "Data Service.";
private static ObservableCollection<Student> _allStudents = new ObservableCollection<Student>();
public static ObservableCollection<Student> GetStudents()
{
try
{
string server = "127.0.0.1";
string database = "sakila";
string user = "root";
string pswd = "!QAZ2wsx";
connectionString = "Server = " + server + ";database = " + database + ";uid = " + user + ";password = " + pswd + ";SslMode=None;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand getCommand = connection.CreateCommand();
getCommand.CommandText = "SELECT * FROM student";
using (MySqlDataReader reader = getCommand.ExecuteReader())
{
while (reader.Read())
{
_allStudents.Add(new Student() { Student_id = reader.GetInt32(0), Student_name = reader.GetString(1), Student_mark = reader.GetString(2) });
}
}
}
}
catch (MySqlException sqlex)
{
// Handle it :)
}
return _allStudents;
}
public static bool InsertNewStudent(Student newStudent)
{
// Insert to the collection and update DB
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand insertCommand = connection.CreateCommand();
insertCommand.CommandText = "INSERT INTO student(student_id, student_name, student_mark)VALUES(#student_id, #student_name,#student_mark)";
insertCommand.Parameters.AddWithValue("#student_id", newStudent.Student_id);
insertCommand.Parameters.AddWithValue("#student_name", newStudent.Student_name);
insertCommand.Parameters.AddWithValue("#student_mark", newStudent.Student_mark);
insertCommand.ExecuteNonQuery();
return true;
}
}
catch (MySqlException sqlex)
{
return false;
}
}
public static bool UpdateStudent(Student Student)
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand insertCommand = connection.CreateCommand();
insertCommand.CommandText = "Update student Set student_name= #student_name, student_mark=#student_mark Where student_id =#student_id";
insertCommand.Parameters.AddWithValue("#student_id", Student.Student_id);
insertCommand.Parameters.AddWithValue("#student_name", Student.Student_name);
insertCommand.Parameters.AddWithValue("#student_mark", Student.Student_mark);
insertCommand.ExecuteNonQuery();
return true;
}
}
catch (MySqlException sqlex)
{
// Don't forget to handle it
return false;
}
}
public static bool Delete(Student Student)
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand insertCommand = connection.CreateCommand();
insertCommand.CommandText = "Delete from sakila.student where student_id =#student_id";
insertCommand.Parameters.AddWithValue("#student_id", Student.Student_id);
insertCommand.ExecuteNonQuery();
return true;
}
}
catch (MySqlException sqlex)
{
return false;
}
}
}
For updating the database in TwoWay binding way, we can implement is by invoking the data updating method in
PropertyChanged event as follows:
void Person_OnNotifyPropertyChanged(Object sender, PropertyChangedEventArgs e)
{
organization.Update((StudentViewModel)sender);
}
For the completed demo you can download here.

SQLite simple insert query

I'm trying to use SQLite as my storage. I've added reference dll using nuget and using statement as well.
I have
private void SetConnection()
{
sql_con = new SQLiteConnection
("Data Source=c:\\Dev\\MYApp.sqlite;Version=3;New=False;Compress=True;");
}
private void ExecuteQuery(string txtQuery)
{
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
sql_cmd.CommandText = txtQuery;
sql_cmd.ExecuteNonQuery();
sql_con.Close();
}
and I'm sending query txt like this
public void Create(Book book)
{
string txtSqlQuery = "INSERT INTO Book (Id, Title, Language, PublicationDate, Publisher, Edition, OfficialUrl, Description, EBookFormat) ";
txtSqlQuery += string.Format("VALUES (#{0},#{1},#{2},#{3},#{4},#{5},#{6},#{7},{8})",
book.Id, book.Title, book.Language, book.PublicationDate, book.Publisher, book.Edition, book.OfficialUrl, book.Description, book.EBookFormat);
try
{
ExecuteQuery(txtSqlQuery);
}
catch (Exception ex )
{
throw new Exception(ex.Message);
}
}
My db is correctly created and passed book instance with valid data is ok. But exception is thrown always on executing query on this line of code:
sql_cmd.ExecuteNonQuery();
I obviously doing something wrong here but I cannot see.
Update: thrown exception message is
SQL logic error or missing database
unrecognized token: "22cf"
where this 22cf is part of passed book.Id guid string.
Don't EVER insert your data in your statement!
Use prepared statements and bind parameters:
public void Create(Book book) {
SQLiteCommand insertSQL = new SQLiteCommand("INSERT INTO Book (Id, Title, Language, PublicationDate, Publisher, Edition, OfficialUrl, Description, EBookFormat) VALUES (?,?,?,?,?,?,?,?,?)", sql_con);
insertSQL.Parameters.Add(book.Id);
insertSQL.Parameters.Add(book.Title);
insertSQL.Parameters.Add(book.Language);
insertSQL.Parameters.Add(book.PublicationDate);
insertSQL.Parameters.Add(book.Publisher);
insertSQL.Parameters.Add(book.Edition);
insertSQL.Parameters.Add(book.OfficialUrl);
insertSQL.Parameters.Add(book.Description);
insertSQL.Parameters.Add(book.EBookFormat);
try {
insertSQL.ExecuteNonQuery();
}
catch (Exception ex) {
throw new Exception(ex.Message);
}
}
To insert the records into the SqliteDB:
using System.Data.SQLite;
private void btnInsert_Click(object sender, RoutedEventArgs e)
{
string connection = #"Data Source=C:\Folder\SampleDB.db;Version=3;New=False;Compress=True;";
SQLiteConnection sqlite_conn = new SQLiteConnection(connection);
string stringQuery ="INSERT INTO _StudyInfo"+"(Param,Val)"+"Values('Name','" + snbox.Text + "')";//insert the studyinfo into Db
sqlite_conn.Open();//Open the SqliteConnection
var SqliteCmd = new SQLiteCommand();//Initialize the SqliteCommand
SqliteCmd = sqlite_conn.CreateCommand();//Create the SqliteCommand
SqliteCmd.CommandText = stringQuery;//Assigning the query to CommandText
SqliteCmd.ExecuteNonQuery();//Execute the SqliteCommand
sqlite_conn.Close();//Close the SqliteConnection
}
Update most recent version using Dapper (Dapper.2.0.90) and SQLite (System.Data.SQLite.Core.1.0.114.2)
using System.Data.SQLite;
using Dapper;
connection string (DB name - 'Store.db')
connectionString="Data Source=.\Store.db;Version=3;"
Person save method in my application
public static void SavePerson(PersonModel person)
{
using (IDbConnection cnn = new SQLiteConnection(connectionString))
{
cnn.Execute("insert into Person (FirstName, LastName) values (#FirstName, #LastName)", new { person.FirstName, person.LastName} );
}
}
person model
public class PersonModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return $"{ FirstName } { LastName }";
}
}
}
This answer includes the code methods I used and use in my applications.
You should use (') when sending string into INSERT statement
VALUES (#{0},'#{1}','#{2}','#{3}','#{4}','#{5}','#{6}','#{7}',{8})
you should also catch SQLExeprion

saving object to database c#

I'm having class Report and class Program, what I want to accomplish (no luck so far) is to send data from class Program and method SaveRep() to class Report method Save() and save it in this method.
I apologize if the question is badly formulated, I am really stuck at this, please help. Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
namespace Application
{
class Program
{
static void Main(string[] args)
{
//call method SaveRep
}
public void SaveRep(...)
{
int RepID = 1;
string Data1 = "SomeData1"
string Data2 = "SomeData2"
//This method should send the data above to method Save() in Report class
//data to this method will be provided from another method.
}
}
public class Report
{
private static int _repID;
public int RepID
{
get { return _repID; }
set { _repID = value; }
}
private static string _data1;
public string Data1
{
get { return _data1; }
set { _data1 = value; }
}
private static string __data2;
public string Data1
{
get { return _data2; }
set { _data2 = value; }
}
public void Save()
{
string strConnectionString = (#"server=(local)\sqlexpress;Integrated Security=True;database=DataBase");
SqlConnection connection = new SqlConnection(strConnectionString);
connection.Open();
// This method should save all data (RepID,Data1,Data2)
// to the DB, provided to her by SaveRep method from Program class.
// Properties are columns from a database
}
}
}
public void Save()
{
string yourConnString="Replace with Your Database ConnectionString";
using(SqlConnection connection = new SqlConnection(yourConnString))
{
string sqlStatement = "INSERT Table1(Data1) VALUES(#Data1)";
using(SqlCommand cmd = new SqlCommand(sqlStatement, connection))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Data1",Data1);
//add more parameters as needed and update insert query
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
//log error
}
}
}
}
Assuming your Data1 is the name of your Column name. Update the sqlStatement to have your relevant columns.
Now in SaveRep, you can call it like
public void SaveRep()
{
Report objReport=new Report();
objReport.Data1="Something somethinng";
objReport.Save();
}
string connectionString = ....; //adjust your connection string
string queryString = "INSERT INTO ....;"; //Adjust your query
using (SqlConnection connection = new SqlConnection(
connectionString))
{
using( SqlCommand command = new SqlCommand(
queryString, connection))
{
connection.Open();
command .ExecuteNonQuery();
}
}
One tiny thing that the previous speakers have not noticed, is that your Report class is severely broken. Why did you use static keywords on the variables? Do not do that! Well, unless you know what it does, and here I have the feeling you don't. Update your Report class to look like this:
public class Report
{
public int RepID {get;set;}
public string Data1 {get;set;}
public string Data2 {get;set;}
public void Save()
{
// what others said
}
}
'static' in your original code makes all te variables global/shared. That means that if you'd create 500 Report objects with new, they all would have the same one ID, Data1 and Data2. Any change to any single of those 500 objects would cause all the objects to change. But it's be misleading, the objects would not change. They would simply have the same data. Looking at the "ID" field, I think you'd rather want a separate objects with separate data for separate records..

Categories