Is there a way to accept null in resultset - sql-server

I am trying to view data from the SQL Server and I have a column (note) that accept null value because it is not necessary for the user to input any values. I tried using the "rs.wasNull" method as below:
var Note : String = rs.getString("note")
if(rs.wasNull()){
Note = ""
}
But I have still facing the error saying that the "rs.getString("note) cannot be null. Is there any possible ways to return null value?
Below are my whole code:
private fun displayData() {
val sqlCon = SQLCon()
connection = sqlCon.connectionClass()!!
var cUser : String? = intent.getStringExtra("Current User")
if (connection == null) {
Toast.makeText(this, "Failed to make connection", Toast.LENGTH_LONG).show()
} else {
try {
val sql : String=
"SELECT * FROM Goals where Username = '$cUser' "
statement = connection!!.createStatement()
var rs : ResultSet = statement!!.executeQuery(sql)
while (rs.next())
{
var Note : String = rs.getString("note")
if(rs.wasNull()){
Note = ""
}
gList.add(GoalList(rs.getString("gName"), rs.getDouble("tAmount"), rs.getDouble("sAmount"), rs.getString("note"), rs.getString("date")))
}
rs.close()
statement!!.close()
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show()
} catch (e: Exception) { Log.e("Error", e.message!!) }
}
}

You use non-nullable return type for note variable:
var Note : String = rs.getString("note")
First, the variable name should start with a lowercase letter -> note.
Secondly, return value must be nullable
var note : String? = rs.getString("note")
In accordance with JavaDoc getString function:
Returns: the column value; if the value is SQL NULL, the value
returned is null
So no need to check if it was null or not, you can use the following construction to pass default value:
var note : String = rs.getString("note") ?: ""

Related

Trying to display name of users on support action bar

Please i am new to kotlin and i have been trying to retrive the fullname of my users in the data base after using getStringExtra so i can use each of them for the title of my support action bar but the value it returns an empty value.
val name = intent.getStringExtra("fullname")
val receiverUid = intent.getStringExtra("uid")
val senderUid = FirebaseAuth.getInstance().currentUser?.uid
mDbRef = FirebaseDatabase.getInstance().getReference()
senderRoom = receiverUid + senderUid
receiverRoom = senderUid + receiverUid
supportActionBar?.title = name
Here is how i am sending name and receiverUid to my database
sendButton.setOnClickListener{
val message = messageBox.text.toString()
val messageObject = Message(message, senderUid)
val name = name.toString()
val receiverUid = receiverUid.toString()
val chatlistObject = ModelChatList(name, message, receiverUid)
mDbRef.child("chats").child(senderRoom!!).child("messages").push()
.setValue(messageObject).addOnSuccessListener {
mDbRef.child("chats").child(receiverRoom!!).child("messages").push()
.setValue(messageObject).addOnSuccessListener {
mDbRef.child("Chatlist").push().setValue(chatlistObject)
}
}
messageBox.setText("")
But when i try to retrive my ModelChatlist object it returns only two values leaving out the receivername as shown in the ModelChatlist below
class ModelChatList {
private var receivername:String = ""
private var lastmessage:String = ""
private var uid:String = ""
constructor(){}
constructor(receivername: String, lastmessage:String, uid:String){
this.receivername = receivername
this.lastmessage = lastmessage
this.uid =uid
}
fun getReceivername(): String{
return receivername
}
fun setReceivername(receivername: String){
this.receivername= receivername
}
fun getUid(): String{
return uid
}
fun setUid(uid: String){
this.uid= uid
}
fun getLastmessage(): String{
return lastmessage
}
fun setLastmessage(lastmessage: String){
this.lastmessage= lastmessage
}
}
In case you are wondering, "fullname" is in my database as the name the users enter when they sign up. Thank You

Snowflake stored procedure variable binding error

I am trying to create and execute a simple Snowflake stored procedure which takes an input argument and creates a stage. However, when I try to call the procedure it throws
ERROR: invalid value [:] for parameter
create or replace procedure raw.test.create_stage_test(PARM_URL string)
returns string
language javascript
execute as owner
as
$$
var cmd = `create or replace stage raw.test.agency_type_test
url =:1
file_format = (type = json)
credentials = (aws_role = 'arn:aws:iam::myrole');`
var sql_statement = snowflake.createStatement({
sqlText: cmd,
binds: [PARM_URL]
});
try {
var rs = sql_statement.execute();
rs.next()
rcount = rs.getColumnValue(1);
if (rcount == 0){
throw "row count is 0";
}
return "Rows count: " + rcount;
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
$$;
CALL raw.test.create_stage_test('s3://mybucket');
Perhaps using interpolation, as in the following code snippet, could be an alternative? Note the single quotes included around the url value:
var cmd = `create or replace stage agency_type_test
url='${PARM_URL}'
file_format = (type = json)
credentials = (aws_role = 'arn:aws:iam::myrole');`
var sql_statement = snowflake.createStatement({
sqlText: cmd
});

AngularJs, how to set empty string in URL

In the controller I have below function:
#RequestMapping(value = "administrator/listAuthor/{authorName}/{pageNo}", method = { RequestMethod.GET,
RequestMethod.POST }, produces = "application/json")
public List<Author> listAuthors(#PathVariable(value = "authorName") String authorName,
#PathVariable(value = "pageNo") Integer pageNo) {
try {
if (authorName == null) {
authorName = "";
}
if (pageNo == null) {
pageNo = 1;
}
return adminService.listAuthor(authorName, pageNo);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This function fetches and returns data from mysql database based on "authorName" and "pageNo". For example, when "authorName = a" and "pageNo = 1" I have:
Data I get when "authorName = a" and "pageNo = 1"
Now I want to set "authorName" as ""(empty string), so that I can fetch all the data from mysql database (because the SQL statement "%+""+%" in backend will return all the data).
What can I do if I want to set authorName = empty string?
http://localhost:8080/spring/administrator/listAuthor/{empty string}/1
Thanks in advance!
I don't think that you can encode empty sting to url, what I suggest you to do is to declare some constant that will be your code to empty string - such as null.
Example:
administrator/listAuthor/null/90
Afterwards , on server side, check if authorName is null and set local parameter with empty stirng accordingly.

The given key was not present in the dictionary solrnet

Please note: I know for the question SolrNet - The given key was not present in the dictionary and I have initialized solr object just like Mauricio suggests.
I am using solr 4.6.0 and solrnet build #173, .net framework 4.0 and VS2012 for development. For some unknown reason I am receiving error 'The given key was not present in the dictionary'. I have a document with that id in solr, I've checked via browser. It's a document like any other document. Why is error popping up? My code (I've made a comment on the place where the error happens):
//establishes connection with solr
private void ConnectToSolr()
{
try
{
if (_solr != null) return;
Startup.Init<Register>(SolrAddress);
_solr = ServiceLocator.Current.GetInstance<ISolrOperations<Register>>();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//Returns snippets from solr as BindingSource
public BindingSource GetSnippets(string searchTerm, DateTime? startDate = null, DateTime? endDate = null)
{
ConnectToSolr();
string dateQuery = startDate == null
? ""
: endDate == null
? "savedate:\"" + convertDateToSolrFormat(startDate) + "\"" //only start date
: "savedate:[" + convertDateToSolrFormat(startDate) + " TO " +
convertDateToSolrFormat(endDate) + "]";//range between start and end date
string textQuery = string.IsNullOrEmpty(searchTerm) ? "text:*" : "text:*" + searchTerm + "*";
List<Register> list = new List<Register>();
SolrQueryResults<Register> results;
string currentId = "";
try
{
results = _solr.Query(textQuery,
new QueryOptions
{
Highlight = new HighlightingParameters
{
Fields = new[] { "*" },
},
ExtraParams = new Dictionary<string, string>
{
{"fq", dateQuery},
{"sort", "savedate desc"}
}
});
for (int i = 0; i < results.Highlights.Count; i++)
{
currentId = results[i].Id;
var h = results.Highlights[currentId];
if (h.Snippets.Count > 0)
{
list.Add(new Register//here the error "the given key was not present in the dictionary pops up
{
Id = currentId,
ContentLiteral = h.Snippets["content"].ToArray()[0].Trim(new[]{' ', '\n'}),
SaveDateLiteral = results[i].SaveDate.ToShortDateString()
});
}
}
BindingList<Register> bindingList = new BindingList<Register>(list);
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = bindingList;
return bindingSource;
}
catch(Exception e)
{
MessageBox.Show(string.Format("{0}\nId:{1}", e.Message, currentId), "Solr error");
return null;
}
}
I've found out what's causing the problem: saving empty documents into solr. If I make an empty query (with text:*) through solrnet (usually I do this if I want to see all saved documents) and empty document is one of saved docs, then 'The given key is not present in dictionary pops up'. If all of the documents have text in them, this error doesn't pop up.
If you document contains fields with types other than string and you index null value to a double or integer field you will get the same error.
solr query return the null field as:
<null name="fieldname"/>
should be
<double name="fieldname">0.0</double>
or
<double name="fieldname"/>

Strange error message when using SaveChanges in EF with MVC

I have a dropdownlistfor with values that is not from my database, and when a user select values that does not exist in my database, I want to save it to the database(and if it already exist, I just use the existing data).
This work fine with some of my data(see code for where it does not work)
This is my repository:
public void newPerson(Person addperson)
{
db.Person.AddObject(addperson);
db.SaveChanges(); //This wont work
}
here is my controller:
[HttpPost]
public ActionResult Create(CreateNKIphase1ViewModel model)
{
if (ModelState.IsValid)
{
var goalcard = new GoalCard();
var companyChecker = "";
var dbCompanies = createNKIRep.GetCustomerByName();
var addcustomer = new Customer();
foreach (var existingcustomer in dbCompanies)
{
companyChecker = existingcustomer.CompanyName;
if (existingcustomer.CompanyName == model.CompanyName)
{
var customerId = existingcustomer.Id;
var selectedCustomerID = createNKIRep.GetByCustomerID(customerId);
goalcard.Customer = selectedCustomerID;
break;
}
}
if (companyChecker != model.CompanyName)
{
addcustomer.CompanyName = model.CompanyName;
createNKIRep.newCustomer(addcustomer); //This works!
goalcard.Customer = addcustomer;
}
if (model.PersonName != null)
{
var Personchecker = "";
var dbPersons = createNKIRep.GetPersonsByName();
foreach (var existingPerson in dbPersons)
{
Personchecker = existingPerson.Name;
if (existingPerson.Name == model.PersonName)
{
var personId = existingPerson.Id;
var selectedPersonID = createNKIRep.GetByPersonID(personId);
goalcard.Person = selectedPersonID;
break;
}
}
if (Personchecker != model.PersonName)
{
Person newPerson = new Person();
newPerson.Name = model.PersonName;
createNKIRep.newPerson(newPerson);//Where repository is called
goalcard.Person = newPerson;
}
}
But when I try to save a new Person I get the following error message:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Even though Person only have Id and name as attributes in my database.
Is there anything wrong in my code, or is it any setting in my database that has to be changed?
Thanks in advance.
It's because I use db.SaveChanges(); multiple times in one post. Reducing numbers of time I use db.SaveChanges helped me get rid of the error.

Resources