Sql数据库是 StudentInfo ,表名是注册
ID----------Name---------------Email---------------------------PhoneNo
1 Munasunghe amilamunasinghe@yahoo.com 0717069425
2 Liyanarachchi hareshliya6@gmail.com 0756706352
protected void Page_Load(object sender, EventArgs e)
{
string query = "select ID, Name, Email, PhoneNo from Registration";
SqlCommand cmd1 = new SqlCommand(query);
DataTable dt1 = GetData(cmd1);
int rowcount = dt1.Rows.Count;
/* I want to read data in each row step by step and assign to variables*/
}
函数 GetData 用于从数据库中获取数据。
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
ID是主键。
结果应该是(名称,电子邮件,电话号码是变量和1,2,...是ID值)
Name[1]=Munasunghe
Name[2]=Liyanarachchi
Email[1]=amilamunasinghe@yahoo.com
Email[2]=hareshliya6@gmail.com
Phone No[1]=0717069425
Phone No[2]=0756706352
答案 0 :(得分:0)
我会说你首先创建一个用于存储数据的新类(如StudentInfo)
public class StudentInfo
{
public StudentInfo(int ID, string Name, string Email, string PhoneNo)
{
this.ID = ID;
this.Name = Name;
this.Email = Email;
this.PhoneNo = PhoneNo;
}
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNo { get; set; }
}
然后使用此函数返回一个StudentInfo类的列表
public List<StudentInfo> GetData()
{
List<StudentInfo> data = new List<StudentInfo>();
SqlConnection con = new SqlConnection("Your connection string");
SqlCommand command = new SqlCommand("SELECT * FROM [Registration]", con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
while(sdr.Read())
{
data.Add((int)sdr["ID"], (string)sdr["Name"], (string)sdr["Email"], (string)sdr["PhoneNo"]);
}
con.Close();
return data;
}
然后你就这样使用它:
List<StudentInfo> info = GetData();
foreach(StudentInfo si in info)
{
Response.Write("<h3>ID is " + si.ID + "</h3><p>StudentName is " + si.Name + "</p>");
}
要更新值,请执行以下操作:
public void SetValue(int StudentID, String NewName, String NewEmail, String NewPhone)
{
SqlConnection con = new SqlConnection("Your connection string");
SqlCommand command = new SqlCommand("UPDATE [Registration] SET [Name]='" + NewName + "', [Email]='" + NewEmail + "', [PhoneNo]='" + NewPhone + "' WHERE [ID]=" + StudentID + "", con);
con.Open();
command.ExecuteNonQuery();
con.close();
}
我建议你阅读一些关于sql的文章