결과가 반환되지 않는 경우의 ExecuteScalar() 처리
.ExecuteScalar()Oracle 이 oracle oracle oracle oracle oracle oracle oracle oracle :
sql = "select username from usermst where userid=2"
string getusername = command.ExecuteScalar();
다음 오류 메시지가 나타납니다.
System.NullReferenceException:개체 참조가 개체의 인스턴스로 설정되지 않았습니다.
는 데이터베이스 에 "Database"의 때 합니다.userid=2.
는는 이이 황떻 떻떻 떻? ???
DbCommand에 대한 MSDN 문서에 따릅니다.Execute Scalar:
결과 집합에서 첫 번째 행의 첫 번째 열을 찾을 수 없는 경우 Null 참조(Visual Basic에서 없음)가 반환됩니다.데이터베이스의 값이 null일 경우 쿼리는 DBNull을 반환합니다.가치.
다음의 스니펫을 검토해 주세요.
using (var conn = new OracleConnection(...)) {
conn.Open();
var command = conn.CreateCommand();
command.CommandText = "select username from usermst where userid=2";
string getusername = (string)command.ExecuteScalar();
}
실행 시(ODP에서 테스트됨).NET 단, 모든 ADO에서는 동일해야 합니다.NET 프로바이더)는 다음과 같이 동작합니다.
- 하지 않는 는, 「」의 입니다.
command.ExecuteScalar()null입니다.이늘 늘, "null", "null", "null"에 됩니다.getusername. - NULL의 입니다.
command.ExecuteScalar()DBNull.Value그 「」가 .InvalidCastException.
경우든, 「」는NullReferenceException불가능하기 때문에 아마 다른 곳에 문제가 있을 것입니다.
먼저 명령 개체가 null이 아닌지 확인해야 합니다.그런 다음 명령어를 설정해야 합니다.SQL 쿼리에 대한 명령어 텍스트 속성입니다.마지막으로 반환값을 오브젝트 변수에 저장하고 null인지 확인한 후 사용해야 합니다.
command = new OracleCommand(connection)
command.CommandText = sql
object userNameObj = command.ExecuteScalar()
if (userNameObj != null)
string getUserName = userNameObj.ToString()
...
VB 구문에 대해서는 잘 모르겠지만 이해하실 수 있을 겁니다.
그냥 이렇게 썼어요.
int? ReadTerminalID()
{
int? terminalID = null;
using (FbConnection conn = connManager.CreateFbConnection())
{
conn.Open();
FbCommand fbCommand = conn.CreateCommand();
fbCommand.CommandText = "SPSYNCGETIDTERMINAL";
fbCommand.CommandType = CommandType.StoredProcedure;
object result = fbCommand.ExecuteScalar(); // ExecuteScalar fails on null
if (result.GetType() != typeof(DBNull))
{
terminalID = (int?)result;
}
}
return terminalID;
}
다음 행:
string getusername = command.ExecuteScalar();
...는 다음과 같이 결과를 암묵적으로 문자열로 변환하려고 합니다.
string getusername = (string)command.ExecuteScalar();
개체가 null인 경우 일반 캐스팅 연산자가 실패합니다.다음과 같이 as-operator를 사용해 보십시오.
string getusername = command.ExecuteScalar() as string;
sql = "select username from usermst where userid=2"
var _getusername = command.ExecuteScalar();
if(_getusername != DBNull.Value)
{
getusername = _getusername.ToString();
}
아래 예를 참조하십시오.
using System;
using System.Data;
using System.Data.SqlClient;
class ExecuteScalar
{
public static void Main()
{
SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
mySqlConnection.Open();
int returnValue = (int) mySqlCommand.ExecuteScalar();
Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);
mySqlConnection.Close();
}
}
SQL NULL 값
- C#은 DBNull입니다.값
- NULLAB의 경우LE 열에 값이 없습니다. 반환되는 값입니다.
- : SQL 비교:
IF ( value IS NULL ) - 의 비교: C#의 비교:
if (obj == DBNull.Value) - 으로 C#Quick-Watch로 됩니다.
{}
데이터 리더에서 읽을 때의 베스트 프랙티스:
var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());
제 경험으로는 반환된 값이 누락되어 null을 반환함으로써 실행이 실패할 수 있습니다.예를 들면 다음과 같습니다.
select MAX(ID) from <table name> where <impossible condition>
MAX를 사용하다래서실실 실실실다다과 ).null)
var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));
둘 중 하나를 원하시면string또는empty string어떤 것이 null일 경우, 아무것도 파손되지 않을 수 있습니다.
using (var cmd = new OdbcCommand(cmdText, connection))
{
var result = string.Empty;
var scalar = cmd.ExecuteScalar();
if (scalar != DBNull.Value) // Case where the DB value is null
{
result = Convert.ToString(scalar); // Case where the query doesn't return any rows.
// Note: Convert.ToString() returns an empty string if the object is null.
// It doesn't break, like scalar.ToString() would have.
}
return result;
}
행을 읽기 전에 항상 확인하세요.
if (SqlCommand.ExecuteScalar() == null)
{
}
이게 제일 쉬운 방법이에요
sql = "select username from usermst where userid=2"
object getusername = command.ExecuteScalar();
if (getusername!=null)
{
//do whatever with the value here
//use getusername.toString() to get the value from the query
}
이 경우 레코드가 존재하지 않습니다.userid=2또는 첫 번째 열에 null 값이 포함되어 있을 수 있습니다. SQL 명령에서 사용되는 쿼리 결과에 대한 값을 찾을 수 없는 경우,ExecuteScalar()돌아온다null.
또는 DataTable을 사용하여 행이 있는지 확인할 수 있습니다.
SqlCommand cmd = new SqlCommand("select username from usermst where userid=2", conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
string getusername = "";
// assuming userid is unique
if (dt.Rows.Count > 0)
getusername = dt.Rows[0]["username"].ToString();
private static string GetUserNameById(string sId, string connStr)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
System.Data.SqlClient.SqlCommand command;
try
{
// To be Assigned with Return value from DB
object getusername;
command = new System.Data.SqlClient.SqlCommand();
command.CommandText = "Select userName from [User] where userid = @userid";
command.Parameters.AddWithValue("@userid", sId);
command.CommandType = CommandType.Text;
conn.Open();
command.Connection = conn;
//Execute
getusername = command.ExecuteScalar();
//check for null due to non existent value in db and return default empty string
string UserName = getusername == null ? string.Empty : getusername.ToString();
return UserName;
}
catch (Exception ex)
{
throw new Exception("Could not get username", ex);
}
finally
{
conn.Close();
}
}
약간의 추측입니다.스택에 예외가 있는지 체크하면 ADO에 의해 스택이 느려집니다.Oracle용 NET 공급자가 첫 번째 값을 얻기 위해 기본 행 집합을 읽는 중입니다.
행이 없으면 찾을 값이 없습니다.
이 경우를 처리하려면 판독기와 핸들 실행Next()일치하지 않는 경우 거짓으로 반환한다.
Microsoft Application Block DLL에서 이렇게 사용(DAL 작업을 위한 도움말 라이브러리)
public string getCopay(string PatientID)
{
string sqlStr = "select ISNULL(Copay,'') Copay from Test where patient_id=" + PatientID ;
string strCopay = (string)SqlHelper.ExecuteScalar(CommonCS.ConnectionString, CommandType.Text, sqlStr);
if (String.IsNullOrEmpty(strCopay))
return "";
else
return strCopay ;
}
VS2010에서 본 적이 있다string getusername = command.ExecuteScalar();컴파일 오류가 표시됩니다.유형 개체를 문자열로 암묵적으로 변환할 수 없습니다.그래서 당신은 글을 쓸 필요가 있다.string getusername = command.ExecuteScalar().ToString();데이터베이스에 레코드가 없는 경우 오브젝트 참조가 오브젝트의 인스턴스로 설정되지 않은 경우 및 코멘트할 때 오류가 발생합니다.ToString()", 에러는 발생하지 않습니다.그래서 나는 말할 수 있는 건ExecuteScalar예외는 없습니다.나는 @Rune Grimstad가 준 답변자가 옳다고 생각한다.
데이터베이스에 연결하는 사용자에게 CONNECT 권한은 있지만 데이터베이스에서 읽을 수 있는 권한이 없을 때 이 문제가 발생했습니다.저 같은 경우에는 이런 것도 할 수 없었어요.
object userNameObj = command.ExecuteScalar()
이것을 try/catch에 넣는 것(어쨌든 당신은 그것을 해야 한다)이 부족한 허가 문제를 해결할 수 있는 유일한 방법이었다.
object objUserName;
objUserName = command.ExecuteScalar();
if (objUserName == null) //if record not found ExecuteScalar returns null
{
return "";
}
else
{
if (objUserName == DBNull.Value) //if record found but value in record field is null
{
return "";
}
else
{
string getusername = objUserName.ToString();
return getusername;
}
}
/* 존재하지 않는 int를 선택합니다.* /
int x = ((int)(SQL_Cmd).Execute Scalar() ? ? ? 0 ) ;
함수 반환값으로 vb 코드에서 다음을 사용했습니다.
obj <> 아무것도 아닌 경우 obj를 반환합니다.ToString() 그렇지 않으면 "종료(End If)를 반환한다.
이 코드를 사용해 보세요.문제가 해결되는 것 같습니다.
Dim MaxID As Integer = Convert.ToInt32(IIf(IsDBNull(cmd.ExecuteScalar()), 1, cmd.ExecuteScalar()))
Oracle을 사용하고 있습니다.SQL이 숫자 값(int)을 반환하는 경우 변환을 사용해야 합니다.ToInt32(개체).다음은 예를 제시하겠습니다.
public int GetUsersCount(int userId)
{
using (var conn = new OracleConnection(...)){
conn.Open();
using(var command = conn.CreateCommand()){
command.CommandText = "select count(*) from users where userid = :userId";
command.AddParameter(":userId", userId);
var rowCount = command.ExecuteScalar();
return rowCount == null ? 0 : Convert.ToInt32(rowCount);
}
}
}
이거 드셔보세요
sql = "select username from usermst where userid=2"
string getusername = Convert.ToString(command.ExecuteScalar());
언급URL : https://stackoverflow.com/questions/1999020/handling-executescalar-when-no-results-are-returned
'programing' 카테고리의 다른 글
| django REST 프레임워크에서 request.data를 수정하는 방법 (0) | 2023.04.01 |
|---|---|
| 워드프레스에 프로그래밍 방식으로 로그인하는 방법 (0) | 2023.04.01 |
| IE8의 스타일 특성 내에서 AngularJS 식이 작동하지 않습니다. (0) | 2023.04.01 |
| 코드 가능을 사용하여 JSON으로 시리얼화할 때 Swift 문자열 이스케이프 (0) | 2023.04.01 |
| React에서 불변성 도움말을 사용하여 변수 개체 키 설정 (0) | 2023.04.01 |