protected void populateDataGrid()
{
string connectionString = configurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
string command = "select * from student";
SqlDataAdapter dataAdapter = new SqlDataAdapter(command, connectionString);
DataSet data = new DataSet();
dataAdapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = @"INSERT INTO [student] (studentID, studentFirstName, studentLastName)
VALUES (" + TextID.Text + ", '" + TextFirstName.Text + "', '" + TextLastName.Text + "')";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
첫 번째 함수는 모든 테이블 데이터를 가져 와서 gridview에 덤프합니다. 두 번째 함수는 입력을 받아서 데이터베이스에 삽입합니다. 이러한 기능을 요약하거나 단순화 할 수있는 방법은 무엇입니까?SQL 연결을 사용하는 최적의 표준 방법은 무엇입니까?
안녕하세요, 클래스 호출 학생을 만들고 거기에 연결 문자열을 비공개로두고 메소드를 삽입하고 메소드를 추가하십시오. 문자열 연결을 피하고 매개 변수를 @ –
과 함께 사용하지 마십시오. 거기에 모든 db 함수가있는 dbhelper 클래스를 작성하고 학생 클래스에서 호출하십시오. –