奇怪!同一條sql語句在資料庫和程式碼中執行結果不同?!當然是人錯了 ……
阿新 • • 發佈:2019-01-28
sql語句就是它:
select count(1) from syscolumns where [id]=object_id( 'tablecommon' )
判斷資料庫中是否存在表tablecommon,本想讓在資料庫中查到的值返回到程式裡,值卻總不是想要的:
程式裡返回 -1
sql裡返回大於0的值(意為存在該表)
如果程式碼正確的話,程式裡應該返回和sql裡一樣的值
程式裡是這麼寫的:
D層類:
SqlHelper類:
執行不帶引數的查詢儲存過程或sql語句:
public DataTable ExecuteQuery(string cmdText, CommandType cmdType) { DataTable dt = new DataTable(); cmd = new SqlCommand(cmdText, GetConn()); cmd.CommandType = cmdType; using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { dt.Load(sdr); } return dt; }
執行不帶引數的增刪改儲存過程或sql語句:
public int ExecuteNonQuery(string cmdText, CommandType cmdType) { int res; try { cmd = new SqlCommand(cmdText, GetConn()); cmd.CommandType = cmdType; res = cmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return res; }
看到這裡有沒有發現我犯的錯誤?
沒錯,我呼叫SqlHelper方法調錯了,咱們開始縷:
我寫的是一個select語句,是用來查詢的,雖然返回結果可以用來直觀判斷表的存在與否,但不能直接呼叫返回值是int型別的增刪改方法!
仍需呼叫返回值是datatable型別的查詢方法,之後將datatable中的值強制轉換為int型別
所以,接下來,將D層類修改下,就搞定了!
public bool IsExitsTable() { Boolean flag = false; string sql = "IfExistsTable"; DataTable dt=sqlhelper.ExecuteQuery(sql,CommandType.StoredProcedure); int res = Convert.ToInt32(dt.Rows[0][0]); if (res > 0) { flag = true; return flag; } else { return flag; } }