Checking Null Cells within MySql Table - mysql

i just wander if there is away to check MySql asp Table if its Cells has Values or Not .
i'v used this to return if Database has Row/Record there
string ConnectionString = #"Server=MYSQL5011.Smarterasp.net;Database=db_9d6c52_ahmed;Uid=9d6c52_ahmed;Pwd=******;";
MySqlConnection GetConnection = new MySqlConnection(ConnectionString);
GetConnection.Open();
string VoiceorScreenSearch = "Select User_Voice ,User_Screen From User where User_Stat=#UserStat";
MySqlCommand Comand = new MySqlCommand(VoiceorScreenSearch, GetConnection);
Comand.Parameters.AddWithValue(#"UserStat", key);
MySqlDataReader ReadData = Comand.ExecuteReader();
if (ReadData.HasRows)
{
hasrowsornot = true;
}
but i need it to return if Cell[1] is null or Has data !, My Cells Datatype is BLOB
and tips of doing this ? , will be helpful
Thanks

You can try like this:
if (!ReadData.IsDbNull(yourfield)) {
var value = ReadData.GetString(yourfield);
// some code
}

Related

xamarin mysql command show Index was outside the bounds of the array

I'm trying to insert data into mysql database.
I'm using mysqlConnector.
But after I confirm insertion with my code.
Debugger returns Index was outside the bounds of the array
Here is my code of insertion:
if (co.OpenConnection() == true)
{
string query = "INSERT INTO inventory (flItem) VALUES('" + ItemName.Text + "');";
MySqlCommand cmd = new MySqlCommand(query, co.connection);
//MySqlDataReader reader = cmd.ExecuteReader();
cmd.ExecuteReader();
await DisplayAlert("TEST", cmd.CommandText, "OK");
await Navigation.PushAsync(new AppShell());
}
Thanks for any help in advance.

How to call stored procedure in Entity Framework Core with input and output parameters using mysql

I am using ASP.net Core 2.2 with Entity Framework core 2.2.6 and Pomelo.EntityFrameworkCore.MySql 2.2.0 for connectivity with MySQL, I have a stored procedure which takes 3 input parameters and 1 output parameter. I am able to call it in MySQL workbench like
CALL GetTechniciansByTrade('Automobile', 1, 10, #total);
select #total;
Now I want to call this using entity framework core, the code I am currently using is
var outputParameter = new MySqlParameter("#PageCount", MySqlDbType.Int32);
outputParameter.Direction = System.Data.ParameterDirection.Output;
var results = await _context.GetTechnicians.FromSql("Call GetTechniciansByTrade(#MyTrade, #PageIndex, #PageSize, #PageCount OUT)",
new MySqlParameter("#MyTrade", Trade),
new MySqlParameter("#PageIndex", PageIndex),
new MySqlParameter("#PageSize", PageSize),
outputParameter).ToListAsync();
int PageCount = (int)outputParameter.Value;
Exception I am getting currently is
Only ParameterDirection.Input is supported when CommandType is Text (parameter name: #PageCount)
Can you try below things.
Use exec instead of call
var results = await _context.GetTechnicians.FromSql("EXEC GetTechniciansByTrade(#MyTrade, #PageIndex, #PageSize, #PageCount OUTPUT)"
Select PageCount in stored procedure
I got information from this github issue.
I found the solution using #matt-g suggestion based on this Question.
I had to use ADO.net for this as
var technicians = new List<TechnicianModel>();
using (MySqlConnection lconn = new MySqlConnection(_context.Database.GetDbConnection().ConnectionString))
{
lconn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = lconn;
cmd.CommandText = "GetTechniciansByTrade"; // The name of the Stored Proc
cmd.CommandType = CommandType.StoredProcedure; // It is a Stored Proc
cmd.Parameters.AddWithValue("#Trade", Trade);
cmd.Parameters.AddWithValue("#PageIndex", PageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.AddWithValue("#PageCount", MySqlDbType.Int32);
cmd.Parameters["#PageCount"].Direction = ParameterDirection.Output; // from System.Data
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
technicians.Add(new TechnicianModel()
{
City = reader["City"].ToString(),
ExperienceYears = reader["ExperienceYears"] != null ? Convert.ToInt32(reader["ExperienceYears"]) : 0,
Id = Guid.Parse(reader["Id"].ToString()),
Name = reader["Name"].ToString(),
Qualification = reader["Qualification"].ToString(),
Town = reader["Town"].ToString()
});
}
}
Object obj = cmd.Parameters["#PageCount"].Value;
var lParam = (Int32)obj; // more useful datatype
}
}

How to Add a shapefile data to postgis(postgres) using c#

am trying to add shapefile data to postgis using c#
string path = browse_path.Text;
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe");
Process p = new Process();
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
p = Process.Start(startInfo);
string chgdir = #"chdir " + #"C:\Program Files\PostgreSQL\9.4\bin\";
p.StandardInput.WriteLine(chgdir);
string pass = #"set PGPASSWORD=postgres";
p.StandardInput.WriteLine(pass);
string cmd = #"shp2pgsql -I -s 4326 " + path + " public.states | psql -U postgres -d postgres";
p.StandardInput.WriteLine(cmd);
p.WaitForExit();
p.Close();`
and for waiting almost 7-8 mins its not working. my shp file is 160 kb only.. but the command is working fine if i run it in the cmd rather then using code..
This is a function I wrote to import shapefiles to PG. It uses Nuget packages CliWrap and Npgsql and I just copied shp2pgsql and its dependencies to a project folder 'Tools' so it can be run on a machine that doesn't have PostgreSQL installed. Its a bit messy and you might need to add error handling but it worked for my needs.
public async static Task<bool> OutputSHPtoPSGLAsync(string shpfile, string host, string user, string pwd, string db, string schema = "public", bool dropIfExists = true, string table = "[SHPNAME]")
{
FileInfo shp = new FileInfo(shpfile);
if (!shp.Exists) return false;
if (table == "[SHPNAME]") table = Path.GetFileNameWithoutExtension(shpfile).ToLower();
string args = string.Format("{0} {1}.{2}", shpfile, schema, table);
Command cli = Cli.Wrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"tools\shp2pgsql.exe")).WithArguments(args);
ExecutionResult eo = await cli.ExecuteAsync();
string sql = eo.StandardOutput;
if (dropIfExists) sql = sql.Replace("CREATE TABLE", string.Format("DROP TABLE IF EXISTS \"{0}\".\"{1}\";\r\nCREATE TABLE", schema, table));
string constring = string.Format("Host={0};Username={1};Password={2};Database={3}", host, user, pwd, db);
using (NpgsqlConnection connection = new NpgsqlConnection(constring))
{
connection.Open();
new NpgsqlCommand(sql, connection).ExecuteNonQuery();
}
return true;
}
I was looking at NetTopologySuite which has type definitions compatible with Npgsql and PostGIS but its all still pre-release and couldn't be bothered working it out.

Headers also inserting into database while upload csv file data

Here headers are also inserting into database .here uploading the csv file with comma separated data
string Feedback = string.Empty;
string connString = ConfigurationManager.ConnectionStrings["DataBaseConnectionString"].ConnectionString;
using (MySqlConnection conn = new MySqlConnection(connString))
{
var copy = new MySqlBulkLoader(conn);
conn.Open();
try
{
copy.TableName = "BulkImportDetails";
copy.FileName = fileName;
copy.FieldTerminator = ",";
copy.LineTerminator = #"\n";
copy.Load();
Feedback = "Upload complete";
}
catch (Exception ex)
{
Feedback = ex.Message;
}
finally { conn.Close(); }
}
return Feedback;
Use the NumberOfLinesToSkip property to skip the first line, like so:
copy.NumberOfLinesToSkip = 1;
The use of this property is clearly shown in the documentation for MySQLBulkLoader. You must make a habit of reading the documentation to resolve your queries before you post a question here.

Convert SqlCommand Output to List<MyType>?

I am using an ADO.NET SqlCommand with a single SqlDbType.Structured parameter to send a table-valued parameter to a sproc. The sproc returns many rows, which I need to get into a strongly-Typed List of . What is the best way to convert the result set (whether DataTable from a DataAdapter or DataReader bits) into List?
Thanks.
You can use LINQ with a DataReader:
var list = reader.Cast<IDataRecord>()
.Select(dr => new YourType { Name = dr.GetString(0), ... })
.ToList();
The most efficient way is using datareader:
var items = new LinkedList<MyClass>();
using(var connection = GetConnection()) {
using(var cmd = connection.CreateCommand()){
cmd.CommandText = "... your SQL statement ...";
// ... add parameters
cnn.Open();
using(var reader = cmd.ExecuteReader()) {
// accessing values via number index is most efficient
//gets index of column with name "PrimaryKey"
var ndxPrimaryKey = reader.GetOrdinal("PrimaryKey");
var ndxColumn1 = reader.GetOrdinal("Column1");
var ndxColumn2 = reader.GetOrdinal("Column2");
while(reader.Read()) {
var item = new MyClass();
// returns value of column "PrimaryKey" typed to nullable Guid
item.PrimaryKey = reader.GetValue(ndxPrimaryKey) as Guid?;
item.Column1 = reader.GetValue(ndxColumn1) as string;
item.Column2 = reader.GetValue(ndxColumn2) as int?;
items.AddLast(item);
}
}
cnn.Close();
}
}
return items;
i think you can use Dapper to convert a query to a class.
for more information see my answer in this link