作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的数据库中有一个名为 students 的表,其中包含编号、姓名、地址....
我有一个表格,我一次加载一个学生的所有信息,我有一个下一步按钮和一个后退按钮。
我如何迭代到 mysql 中的下一行(或上一行)(以便能够看到下一个学生的信息)?
我尝试使用主键(自动递增)进行迭代,当我想查看下一条记录时,我将 id 加 1 或减 1 以查看上一条记录。
但是,如果删除一条记录,它将显示一条空记录。你能给我指出正确的方向吗?
我使用 WinForms
对不起我的英语..
string config = "server=localhost; userid = root; database = databaseName";
MySqlConnection con = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT * FROM students WHERE id = " + id; //id is the primary Key (auto increment)
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
string studentName = (string)reader["studentName"];
string studentNum = (string)reader["studentNum"];
tbstudentName.Text = Convert.ToString(studentName);
tbstudentNum.Text = Convert.ToString(studentNum);
.....
}
con.Close();
最佳答案
您不应该在每次要查看下一条记录时都调用数据库。尝试将所有数据读入列表。
我不确定您使用的是什么.. WinForms?白皮书?
如果是 WinForms,您将需要执行类似的操作。
public class Student
{//First create a class to hold your data in
public string Name { get; set; }
public string Num { get; set; }
}
public class MyForm : Form
{
int Index = 0;
List<Student> FormData { get; set; }
void GetData()
{
//This will hold all your data in memory so you do not have to make a database call each and every "iteration"
List<Student> dbData = new List<Student>();
string config = "server=localhost; userid = root; database = databaseName";
MySqlConnection con = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT * FROM students";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
Student newStudent = new Student();
newStudent.Name = (string)reader["studentName"];
newStudent.Num = (string)reader["studentNum"];
//Add data to the list you created
dbData.Add(newStudent);
.....
}
con.Close();
//set the Form's list equal to the one you just populated
this.FormData = dbData;
}
private void BindData()
{
//If winforms
tbstudentName.Text = FormData[Index].Name;
tbstudentNum.Text = FormData[Index].Num;
//If wpf you will have to use view models and bind your data in your XAML but I am assuming you are using
//winforms here.
}
private void NextRecord()
{ //If you reached the end of the records then this will prevent IndexOutOfRange Exception
if (Index < FormData.Count - 1)
{
Index++;
BindData();
}
}
private void PreviousRecord()
{
if (Index != 0)
{
Index--;
BindData();
}
}
}
现在上面的场景将让它快速工作;但是,有更好的方法可以在您需要更改该数据时帮助您。我会推荐 WinForms 绑定(bind)。你可以在这里查看 http://msdn.microsoft.com/en-us/library/c8aebh9k(v=vs.110).aspx
关于c# - 遍历数据库表行 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21431990/
我是一名优秀的程序员,十分优秀!