2013-06-05 2 views
1

user_Id 및 regNo가있는이 테이블 프로필이 있는데 데이터를 삽입하기 전에 id 및 전자 메일이 이미 있는지 먼저 확인하려고합니다.id 및 reg가 이미 존재하는지 확인

내 코드에서 하나의 행 (ID 또는 등록 번호) 만 유효성을 검사 할 수 있지만 그 중 두 개를 검증하려고하면 "스칼라 변수를 선언해야합니다. 사용자 ID ". 내가 선택한 코드가 잘못되었거나 내 코드에있는 것인지 알 수 없습니다.

SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"); 
    con.Open(); 
    SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = @userid AND RegNo = @reg", con); 

    SqlParameter param = new SqlParameter(); 
    //SqlParameter param1 = new SqlParameter(); 
    param.ParameterName = "@userid"; 
    param.ParameterName = "@reg"; 

    param.Value = txtid.Text; 
    param.Value = txtregNo.Text; 

    cmdd.Parameters.Add(param); 
    //cmdd.Parameters.Add(param1); 


    SqlDataReader reader = cmdd.ExecuteReader(); 


     if (reader.HasRows) 
     { 
      MessageBox("User Id/Registry Number already exists"); 
     } 


     else 
     { 
      SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"); 
      SqlCommand cmd = new SqlCommand("qry", con); 
      cmd.CommandType = System.Data.CommandType.Text; 

      cmd.Parameters.AddWithValue("@id", txtid.Text); 
      cmd.Parameters.AddWithValue("@regno", txtregNo.Text); 
      cmd.Parameters.AddWithValue("@name", txtname.Text); 

      cmd.CommandType = System.Data.CommandType.StoredProcedure; 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      MessageBox("successfully saved!"); 

     } 

저는 asp.net에서 C#을 사용하고 있습니다.

답변

1
param.ParameterName = "@userid"; 
param.ParameterName = "@reg"; 

param.Value = txtid.Text; 
param.Value = txtregNo.Text; 

만 1 개 매개 변수를 선언하고 ParameterNameValue 모두 덮어 쓰기한다.

제쳐두고, 어떤 유형의 데이터 액세스 도우미 또는 ORM 또는 보일러 플레이트 SQL 연결 코드의 문제를 해결하는 방법을 고려해야합니다.

이미 열려있는 SQL 연결의 내부에서 다른 연결을 여는 중입니다.

0

@userid에 할당 한 후이 매개 변수를 @reg에 다시 지정하는 것이 문제입니다.

는 시도이 :

SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"); 
con.Open(); 
SqlCommand cmdd = new SqlCommand("select user_id from Profile where user_Id = @userid AND RegNo = @reg", con); 


cmdd.Parameters.AddWithValue("@userid", txtid.Text); 
cmdd.Parameters.AddWithValue("@reg", txtregNo.Text); 

var id = cmdd.ExecuteReader() as string; 

if (String.IsNullOrEmpty(id)) 
{ 
    //Show error message and exit the method 
} 
else 
{ 
    //Add the row to the database if it didn't exist 
} 

편집 :

내가 사용자 ID가 테이블에 있는지 확인할 수있는 방법을 보여주기 위해 몇 가지 코드를 추가했다. 그런 다음 reader 오브젝트를 확인하는 대신 사용자 ID 자체를 검사합니다. 참고, 내가 지금 내 dev에 컴퓨터 아니에요 그래서 내가 이것을 컴파일하지 않았다, 당신은 몇 가지 개조해야 할 수도 있지만 아이디어가 거기에 있습니다.

+0

답장 보내 주셔서 감사합니다. 나는 당신의 코드 제안을 시도했다.하지만 그것은 단지 regno의 유효성을 검사하는 것입니다, 사용자 ID는 유효성을 검사하지 않습니다, 그것은 심지어 id가 이미 저장되어 있습니다. – user2388316

+0

'id'가 표의 기본 키로 설정되어 있습니까? –

+0

아니요, 내 기본 키가 아닌 ID입니다. – user2388316

0

SQL 매개 변수의 인스턴스 하나를 사용하고 두 개의 다른 값을 전달하므로 첫 번째 인스턴스를 재정의합니다. 이런 식으로 시도 :

SqlParameter param1 = new SqlParameter("@userid", txtid.Text); 

SqlParameter param2 = new SqlParameter("@reg", txtregNo.Text); 
+0

나는 또한 당신의 코드 제안을 시도했다. 하지만 그냥 reg 번호, 사용자 ID가 유효성을 검사하지 않습니다 유효성을 검사하고있다, 심지어 id가 이미 존재합니다 저장 – user2388316

+0

내 게시물은 매개 변수와 함께 귀하의 첫 번째 오류에 관한했다. 어떤 이유로 데이터베이스의 두 필드에 고유 한 인덱스를 추가하지 않으려는 경우, '1에서'를 얻으면 언제나 'select count (1) from user_Id = @userid AND RegNo = @ reg'를 실행할 수 있습니다. '그런 다음 사용자는 이미 다른 삽입물로 진행할 수 있습니다. – Ted

+0

다른'SqlCommand'와'ExecuteReader()'또는'SqlDataAdapter'와'DataSet'을 사용할 수 있습니다. 이 CodeProject를 확인하십시오 http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C – Ted

2

확인을, 그래서이 작동하지 않을 :

SqlParameter param = new SqlParameter(); 
//SqlParameter param1 = new SqlParameter(); 
param.ParameterName = "@userid"; 
param.ParameterName = "@reg"; 

param.Value = txtid.Text; 
param.Value = txtregNo.Text; 

cmdd.Parameters.Add(param); 

같은 개체의 값을 다시 지정하기 때문이다. 여기에 그 변경 :

cmdd.Parameters.AddWithValue("@userid", txtid.Text); 
cmdd.Parameters.AddWithValue("@reg", txtregNo.Text); 

이이 SqlCommand 개체에 매개 변수, 그 중 두 가지를 추가합니다. 이제 좀 더 조언,이 일을 생각해

using (SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True")) 
{ 
    con.Open(); 
    using (SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = @userid AND RegNo = @reg", con)) 
    { 
     ... 

     using (SqlDataReader reader = cmdd.ExecuteReader()) 
     { 
      ... 
     } 
    } 
} 

지금 당신이 그 제대로 개체를 폐기하지 않을 때문이다. IDisposable를 구현

당신이 볼, 아무것도는 Dispose 방법은 그것에라고 확인 using 문에 싸여되어야한다.

관련 문제