Iam not able to retrieve completely the data from sql? - sql-server-2008

public string getString()
{
con.ConnectionString = ConnString;
con.Open();
string sp = "select top 3 hotelid from hotel order by NEWID()";
SqlCommand cmd = new SqlCommand(sp, con);
SqlDataAdapter sa = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
reader = cmd.ExecuteReader();
while (reader.Read()) //Call Read to move to next record returned by SQL //OR call --While(reader.Read())
{
det = reader[0].ToString();
}
reader.Close();
con.Close();
return det;
}
When I'm executing this code I'm able to retrieve only a single item of data?,
but when I am executing the SQL query I am able to retrieve randomly 3 items of data.

You are overwriting the det variable on each while loop.
You either need to create a collection and add to it, or concatenate the string (note the +=)...
det += reader[0].ToString();
UPDATE
As suggested above, another option is to create a collection, something like...
public List<string> getString()
{
...
List<string> ret = new List<string>;
while (reader.Read())
ret.Add(reader[0].ToString());
...
return ret;
}

Related

Json from DataTable returns single element as an array

I'm trying to create an api endpoint that returns an element by id , but JsonResult makes an array from DataTable which is supposed to have only one object
[HttpGet("{id:int}")]
public JsonResult GetUser(int id)
{
string query = #"select id,number,name,lastName from dbo.Users where id=" + id;
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("UsersDb");
SqlDataReader myreader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myComm = new SqlCommand(query, myCon))
{
myreader = myComm.ExecuteReader();
table.Load(myreader);
myreader.Close();
myCon.Close();
}
}
return new JsonResult(table);
}
However i get this result with squared brackets on the sides
[{"id":4,"number":10,"name":"Peter","lastName":"Peterson"}]
try this
return new JsonResult(JArray.FromObject(dt).First())
result
{"id":4,"number":10,"name":"Peter","lastName":"Peterson"}
You can just return table.Rows[0] rather than the whole table.
There are other improvements here:
Parameterize your query. Do not inject data into your SQL.
Missing using on the reader.
Consider making this function async
[HttpGet("{id:int}")]
public JsonResult GetUser(int id)
{
const string query = #"#
select
id,
number,
name,
lastName
from dbo.Users
where id = #id;
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("UsersDb");
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
using (SqlCommand myComm = new SqlCommand(query, myCon))
{
myComm.Parameters.Add("#id", SqlDbType.Int).Value = id;
myCon.Open();
using(var myreader = myComm.ExecuteReader())
{
table.Load(myreader);
}
}
return new JsonResult(table.Rows[0]);
}

Error while trying to get data from the database for login

I have the below code that is supposed to return me a String (either with a value or empty) but instead I am getting the following text value inside the String result "System.Threading.Tasks.UnwrapPromise 1[System.Object]"because of which my call to (String.IsNullOrEmpty(result)) gives an unexpected result.
private bool UserLogin(string un, string pw)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select username from CTM_DATABASE.dbo.users where username=#un and password=#pw", con);
cmd.Parameters.AddWithValue("#un", un);
cmd.Parameters.AddWithValue("#pw", pw);
con.Open();
string result = Convert.ToString(cmd.ExecuteScalarAsync());
if(String.IsNullOrEmpty(result)) return false; return true;
}
Any ideas what I am doing wrong?
PS: it is my first time coding in ASP.net

How to store a Dictionary in a MySQL database?

Can some one demonstrate how I can save the values of a dictionary into a MySQL database?
public void Update()
{
Dictionary<string,int> t = new Dictionary<string,int>();
for(int i = 0; i < t.Count;i++)
{
//What comes Here?
}
}
First fix your iteration loop, second it is up to you to decide, eg:
MySqlConnection conDataBase = new MySqlConnection(constring);
conDataBase.Open();
foreach (KeyValuePair<string, string> entry in)
{
string constring = "..........";
string Query = "insert into Tablename values(#par1,#par2)";
MySqlCommand cmd = new MySqlCommand(Query, conDataBase);
cmd.Parameters.AddWithValue( "#par1",entry.Key)
cmd.Parameters.AddWithValue("#par2",entry.Value)
//Execute command
cmd.ExecuteNonQuery();
}

C# Mysql - The given key was not present in the dictionary

I am trying to execute the following code:
_cmd.CommandText = "SELECT * FROM category";
MySqlDataReader ret;
_cmd.Connection = _con;
_con.Open();
ret = _cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
_con.Close();
return ret;
Yet, I am getting a strange error:
The given key was not present in the dictionary.
The connection string is being read correctly from web.config (I can see this using the debuger). I also have other methods that use the same connectionString (that are used to insert data) and they work correctly. Anything I am missing here?!
This is the method I am trying to invoke:
public MySqlDataReader ExecuteReader(String sql, MySqlParameter[] param)
{
if (param != null)
_cmd.Parameters.AddRange(param);
_cmd.CommandText = sql;
MySqlDataReader ret;
_con.Open();
ret = _cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
return ret;
}
It is invoked from this web service:
[WebMethod]
public string[] GetCategories()
{
String sql = "SELECT CategoryName FROM category";
DatabaseHelper dh = new DatabaseHelper();
MySqlDataReader dr = dh.ExecuteReader(sql, null);
List<String> categories = new List<string>();
while (dr.Read())
{
categories.Add(dr[0].ToString());
}
dr.Close();
return categories.ToArray();
}

Access import into SQL server not importing first line

I am using a function to import data from a access db into SQL server:
public string importDataFromAccess(string table, string fileName)
{
OleDbConnection OleDbConn = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
try
{
string sSQLTable = table;
string myExcelDataQuery = "Select * from " + sSQLTable;
string sSqlConnectionString = connStr;
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
return "Done";
}
catch (Exception ex)
{
OleDbConn.Close();
return ex.ToString();
}
}
I noticed it isnt importing the first record of each table, can anyone help notice why and how to fix? Hopefully it is only the first row...
You shouldn't need the
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
And you just need to replace that with
bulkCopy.WriteToServer(dr);
The WriteToServer method
Copies all rows in the supplied IDataReader to a destination table
specified by the DestinationTableName property of the SqlBulkCopy
object.
But the dr.Read() that you have called has read the first line out of the Reader and advanced the IDataReader to the next record (so it is not accessible to the WriteServer method).