我已经为数据库连接和数据库更新创建了类:
class DatabaseConnection
{
private string sql_string;
private string strCon;
System.Data.SqlClient.SqlDataAdapter da;
public string Sql { set { sql_string = value; } }
public string connection_string { set { strCon = value; }}
public System.Data.DataSet GetConnection{ get { return MyDataSet(); }}
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
一个程序
try
{
objConnect = new DatabaseConnection();
conString = Properties.Settings.Default.GBMRainfallConnectionString;
objConnect.connection_string = conString;
objConnect.Sql = Properties.Settings.Default.SQL;
ds = objConnect.GetConnection;
MaxRows = ds.Tables[0].Rows.Count;
MessageBox.Show(MaxRows.ToString());
//dRow = ds.Tables[0].Rows[100];
//txtFirstName.Text = dRow.ItemArray.GetValue(0).ToString();
//txtSurname.Text = dRow.ItemArray.GetValue(1).ToString();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
string CatchID = @"C:\Users\NKB\Desktop\GBMCatchments.txt";
List<string> CatchmentName = new List<string>();
var catchmet = new StreamReader(File.OpenRead(CatchID));
int x = 0;
while (!catchmet.EndOfStream)
{
var line = catchmet.ReadLine();
CatchmentName.Add(line);
x = x + 1;
}
List<string> Date = new List<string>();
List<string> CatchName = new List<string>();
List<string> CatchRain = new List<string>();
for (int j = 0; j < 360; j++)
{
string catchCSV = "C:\\Users\\NKB\\Desktop\\Catchments\\" + CatchmentName[j] + ".csv";
var catchment = new StreamReader(File.OpenRead(catchCSV));
while (!catchment.EndOfStream)
{
var line = catchment.ReadLine();
var values = line.Split(',');
Date.Add(values[0]);
CatchName.Add(CatchmentName[j]);
CatchRain.Add(values[1]);
}
}
for (int i = 0; i < CatchRain.Count; i++)
{
DataRow row = ds.Tables[0].NewRow();
row[0] = Date[i];
row[1] = CatchName[i];
row[2] = CatchRain[i];
ds.Tables[0].Rows.Add(row);
}
objConnect.UpdateDatabase(ds);
数据保存在数据库中。但是当我关闭程序时,数据库不包含任何数据。它为什么会出现,解决方案是什么?