Saving Object To Database C#
Solution 1:
publicvoidSave()
{
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 querytry
{
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
publicvoidSaveRep()
{
Report objReport=new Report();
objReport.Data1="Something somethinng";
objReport.Save();
}
Solution 2:
string connectionString = ....; //adjust your connection stringstring queryString = "INSERT INTO ....;"; //Adjust your query
using (SqlConnection connection = newSqlConnection(
connectionString))
{
using( SqlCommand command = new SqlCommand(
queryString, connection))
{
connection.Open();
command .ExecuteNonQuery();
}
}
Solution 3:
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:
publicclassReport
{
publicint RepID {get;set;}
publicstring Data1 {get;set;}
publicstring Data2 {get;set;}
publicvoidSave()
{
// 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..
Post a Comment for "Saving Object To Database C#"