i have a table empinf
fields
Empid int
EmpName Nvarchar
Salary Numeric
i have a EmployeeUtility class which contains a Method Getdetails
public EmployeeDetails Getdetails(int employeeId)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SelectEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Id",SqlDbType.Int,4));
cmd.Parameters["#Id"].Value=employeeId;
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (!reader.HasRows) return null;
reader.Read();
EmployeeDetails emp = new EmployeeDetails((int)reader["EmpId"], (string)reader["EmpName"], (int)reader["Salary"]);
reader.Close();
return emp;
}
catch (SqlException e)
{
throw new ApplicationException("Data error.");
}
finally
{
con.Close();
}
}
EmployeeDetails emp=new EmployeeDetails((int)reader["EmpId"],(string)reader["EmpName"],(int)reader["Salary"]);
it shows an error in this line indicating Specified cast is not valid. please need assistance in it.
my employeeDetails class is as follows:
public class EmployeeDetails
{
private int employeeID;
public int EmployeeID
{
get { return employeeID; }
set { employeeID = value; }
}
private string employeeName;
public string EmployeeName
{
get { return employeeName; }
set { employeeName = value; }
}
private int salary;
public int Salary
{
get { return salary; }
set { salary = value; }
}
public EmployeeDetails(int employeeId, string employeeName, int salary)
{
EmployeeID = employeeID;
EmployeeName = employeeName;
Salary = salary;
}
public EmployeeDetails()
{
// TODO: Complete member initialization
}
}
I'm assuming that this error is a runtime exception, and not a compiler error?
The problem is not with your EmployeeDetails class - but on one of these
(int)reader["EmpId"], (string)reader["EmpName"], (int)reader["Salary"]
One or more of the values being populated into the data reader cannot be converted into int or string, either because of a bad type or because it's null.
Since EmpId is likely to be an Identity column, and therefore not null, my money is on either the EmpName column being null or the Salary column actually containing a float, or being null. In the second case, you could use an int?, unless it's just simply dodgy data, in which case make sure the column is not nullable.
You can use the Convert class for converting column values to .net types - because they will actually be Sql types. That said, those types - SqlInt32, for example - does support casting directly to int, for example, but it will also throw an exception if the underlying value is null. That said, so will Convert; so I suppose either will actually do.
This is mostly a guess, but it could be this:
(int)reader["Salary"]
Numeric is a decimal data type, not an integer. But you're trying to directly cast it to an integer. If the Salary value in the database is a decimal, try changing the Salary value on the object to a decimal as well.
Note that you can easily debug this and narrow down the problem in the future by simply removing one field at a time and re-running the test. When you remove a field and it works, re-add the field and it again doesn't work, you've found the culprit.
Note also that your exception handling is woefully poor form:
catch (SqlException e)
{
throw new ApplicationException("Data error.");
}
Not only do you completely ignore the actual exception, but you replace it with another that's entirely devoid of context. You should at least log the exception that occurs.
Try this:
EmployeeDetails emp=new EmployeeDetails(Convert.ToInt32(reader["EmpId"]),Convert.ToString(reader["EmpName"]),Convert.ToInt32(reader["Salary"]));
//this assumes that you don't have NULL values in any of those columns, because if you do, it will fail. It would be more safe to check for DBNull.Value before trying to Cast these values.
Related
i am trying to insert this command in a dynamic way in a unity project:
public static string insertPlayerCmd = "INSERT INTO Player (Name) VALUES (?);";
I am using this method on a repository to insert a name into the database:
public AccountContents SaveAccount(string newName)
{
string name = newName;
var transaction = Finder.DB.DatabaseConnection.BeginTransaction();
var command = Finder.DB.DatabaseConnection.CreateCommand();
AccountContents newAccountContents = null;
try
{
command.CommandText = ConstantDbRequests.insertPlayerCmd;
command.Parameters.Add(newName);
var newAccount = command.ExecuteReader();
transaction.Commit();
newAccountContents = new AccountContents(newAccount.GetInt32(0), newAccount.GetString(1));
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
return newAccountContents;
}
the line command.Parameters.Add(newName); throws an invalid cast exception.
I verified my database in SQLite, and the column to insert is of Text type, all the names on the SQL command are writen correctly, but i can't add the parameter to replace the ? wildcard
Hi i am experiencing this error.
Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF
i have checked my db structure and can insert manually in the db. my code is
public bool Save(SaveTeamAssignedVm data)
{
try
{
var newdata = _unitOfWork.TeamAssignedRepository.Add(new TeamAssigned()
{
CreatedBy = data.CreatedBy,
DateCreated = DateTime.Now,
UpdatedBy = "",
DateUpdated = DateTime.Now,
IsActive = true
});
return true;
}
catch (Exception ex)
{
throw ex;
}
I have not been inserting any sort of data that will interrupt the identity column.
i even removed other data to check if other data is the error but no matter what i it still has the error. any idea on why?
So, I'm creating a desktop banking application. It's nothing too serious, I'm just trying to practice and get better.
// Method I use to get a connection. I know this works.
public static Connection getConnection() throws SQLException {
String sCon = "jdbc:sqlite:banking.sqlite";
Connection connection = DriverManager.getConnection(sCon);
return connection;
}
.
..
...
.....Other code
Method I attempt to use to create and manipulate the data in the result set.
The problem I believe starts here. With this code, I am only able to return one row of the result set and only the last row.
public static Customers getAccounts(Customers c) {
String query = "select RowCount, Customers.Account_Number, "
+ "Customers.First_Name, Last_Name, Address, "
+ "Phone_Number, Accounts.Balance "
+ "from Customers "
+ "join Accounts ";
try (Connection connection = getConnection();
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String fName = rs.getString("First_Name");
String lName = rs.getString("Last_Name");
String address = rs.getString("Address");
String phone = rs.getString("Phone_Number");
String accNum = rs.getString("Account_Number");
String balance = rs.getString("Balance");
c.setFirstName(fName);
c.setLastName(lName);
c.setAddress(address);
c.setPhoneNumber(phone);
c.setAccountNumber(accNum);
c.setBalance(balance);
}
return c;
} catch (SQLException e) {
System.err.println(e);
}
return null;
}
}
Here is the method that is linked to the button I use to perform what I'm trying to attempt. It's part of the Controller class. I believe this method is also a part of the problem. Any ideas? Thank for all you guys do. This website is a real benefit to the community.
public void next() {
Customers c = new Customers();
DBInterface.getAccounts(c);
firstNameF2.setText(c.getFirstName());
lastNameF2.setText(c.getLastName());
addressF2.setText(c.getAddress());
phoneNumberF2.setText(c.getPhoneNumber());
accNumF.setText(c.getAccountNumber());
balanceF.setText(c.getBalance());
}
If you are expecting to get multiple Customers objects, then you definitely should return a list of that.
public static List<Customers> getAccounts() {
// Whatever you originally had...
final List<Customers> ret = new ArrayList<>();
while (rs.next()) {
String fName = rs.getString("First_Name");
String lName = rs.getString("Last_Name");
String address = rs.getString("Address");
String phone = rs.getString("Phone_Number");
String accNum = rs.getString("Account_Number");
String balance = rs.getString("Balance");
final Customers cust = new Customers();
cust.setFirstName(fName);
cust.setLastName(lName);
cust.setAddress(address);
cust.setPhoneNumber(phone);
cust.setAccountNumber(accNum);
cust.setBalance(balance);
ret.add(cust);
}
return ret;
}
I have removed the part about passing in the instance of Customers (which would have ended up as passing in List<Customers>. If you really need to do that, you can add back in and do all the necessary checks.
I have datain my database (shown in the screen)
But the returned values are null? How is that possible, in the output I got this:
This is the code I'm using:
public static SQLiteConnection dbConnection = new SQLiteConnection("RPR_REKENSOFTWARE_DB.db");
public static List<String> GetParts()
{
var items = new List<String>();
try
{
string sSQL = #"SELECT * FROM parts;";
ISQLiteStatement dbState = dbConnection.Prepare(sSQL);
// Get the records
while (dbState.Step() == SQLiteResult.ROW)
{
// Say what it is.
string partNr = dbState[1] as string;
items.Add(partNr);
}
return items;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw ex;
}
}
This is the database I'm using:
The reason is that you are converting the value from database to string, although it is actually an int. You should do:
string partNr = ( ( int )dbState[ 1 ] ).ToString();
Or more simply:
string partNr = dbState[ 1 ].ToString();
The reason is that the row returned from database is contains .NET equivalents of the DB column types and hence dbState[1] is an int. When you use as string on an int however, it cannot be cast and you get null.
I'm very new in programming and this is my first post (question) here, so please don't judge me.
I'm trying to build my first individual WCF service for my project. Let me first display my code , so it will be easier to understand.
This is my data access layer:
public class DataAccessLayer : IDisposable
{
string DBConnectionString = "DBCS";
public int ValidateUser(string employeeLogin, string employeePassword)
{
int outputResult = 0;
try
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create(DBConnectionString);
string storedProcedureName = "uspValidateUser";
DbCommand dbCommand = db.GetStoredProcCommand(storedProcedureName);
db.AddInParameter(dbCommand, "#EmployeeLogin", DbType.String, employeeLogin);
db.AddInParameter(dbCommand, "#EmployeePassword", DbType.String, employeePassword);
db.AddOutParameter(dbCommand, "#OutRes", DbType.Int32, outputResult);
using (IDataReader reader = db.ExecuteReader(dbCommand))
{
Mapper.Reset();
Mapper.CreateMap<IDataReader, Int32>();
outputResult = (int)Mapper.Map<IDataReader, Int32>(reader);
}
}
catch (Exception ex)
{
throw ex;
}
return outputResult;
}
public void Dispose()
{
}
}
This is my stored procedure:
ALTER PROCEDURE [dbo].[uspValidateUser]
#EmployeeLogin VARCHAR(20),
#EmployeePassword VARCHAR(20),
#OutRes int Output
AS
SET #OutRes = (select count(*)
from dbo.tblEmployee
where EmployeeLogin = #EmployeeLogin
and EmployeePassword = #EmployeePassword)
if (#OutRes = 1)
BEGIN
SET NOCOUNT ON;
set #OutRes = 1 --Login is correct
end
else
BEGIN
set #OutRes = 0 -- Login is incorrect
END
And code behind my web form:
public int ValidateUser(string employeeLogin, string employeePassword)
{
int outputResults = 0;
try
{
using (HospitalWCFService.ContractsClient objWCFService = new HospitalWCFService.ContractsClient())
{
outputResults = objWCFService.ValidateUser(employeeLogin, employeePassword);
}
}
catch (Exception ex)
{
lgnEmployeeLogin.FailureText = ex.Message;
}
return outputResults;
}
protected void ValidateUser(object sender, AuthenticateEventArgs e)
{
int outputResults = 0;
outputResults = ValidateUser(lgnEmployeeLogin.UserName, lgnEmployeeLogin.Password);
if (outputResults == 1)
{
Session["UserName"] = lgnEmployeeLogin.UserName.ToString();
FormsAuthentication.RedirectFromLoginPage(lgnEmployeeLogin.UserName, lgnEmployeeLogin.RememberMeSet);
}
else
{
lgnEmployeeLogin.FailureText = "Username and/or password is incorrect.";
}
}
To get user credentials I'm using login control lgnEmployeeLogin.
I'm having problems of retrieving that output integer #OutRes parameter from database using Mapper (I need to use mapper)
If it is possible, please explain solution in easiest language possible as I might not understand difficult technical slang.
Thank you all in advance!
Your lack of answers could be because you say that you have to use mapper - but I chose to ignore that, because ExecuteReader is for dealing with the rows and columns returned by a stored procedure, not for its output parameters. The stored procedure you provided has no result set!
This could be as simple as
db.ExecuteNonQuery();
OutputResult = db.Parameters( "#OutRes").value
to be clear, this replaces your using...ExecuteReader block
Also note: your code did not deal with opening (and closing) the SQL connection (db.Connection.Open();, so I ignored that here too.