我正在上课报告和课程计划,我想要完成的目标(到目前为止没有运气)是将数据从类Program和方法SaveRep()发送到类Report方法Save()并将其保存在此方法中。
如果问题制定得很糟,我很抱歉,我真的很抱歉,请帮忙。感谢
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
}
}
}
答案 0 :(得分:0)
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();
}
}
答案 1 :(得分:0)
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
}
}
}
}
假设您的Data1
是您的列名称。更新sqlStatement以获得相关列。
现在在SaveRep
,您可以将其称为
public void SaveRep()
{
Report objReport=new Report();
objReport.Data1="Something somethinng";
objReport.Save();
}
答案 2 :(得分:0)
前面的发言者没有注意到的一件小事是,你的Report
课程严重受损。为什么在变量上使用static
个关键字?不要那样做!好吧,除非你知道它做了什么,在这里我感觉你没有。将您的报告类更新为:
public class Report
{
public int RepID {get;set;}
public string Data1 {get;set;}
public string Data2 {get;set;}
public void Save()
{
// what others said
}
}
'静态'在原始代码中,所有te变量都是全局/共享的。这意味着,如果您使用new
创建500个报表对象,则它们将具有相同的ID,Data1和Data2。对这500个对象中的任何一个进行任何更改都会导致所有对象发生更改。但它会产生误导,对象不会改变。他们只会拥有相同的数据。看着" ID"字段,我认为您更希望单独的对象具有单独的数据以用于单独的记录。