How to store a Dictionary in a MySQL database? - mysql

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();
}

Related

Assign query result to a variable and return variable

private int getuserid(String username){
SqlConnection con = new SqlConnection(_conString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT USER_ID from tblUser where USERNAME ='" +username+"'";
int locid = Convert.ToInt32(cmd.CommandText);
return locid;
}
Hi everyone, do you have an idea on how to assign value of user_id in a variable and return it. I tried but I am not sure its good.
You need to actually open the connection and run the command.
You should also take measures to protect against sql injection and leaving the connection open in the event of an exception. This code solves all three concerns:
private int getuserid(String username)
{
using (var con = new SqlConnection(_conString))
using (var cmd = new SqlCommand("SELECT user_id FROM tblUser WHERE username = #username", con))
{
// Use actual column type and length from the database
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 30).Value = username;
con.Open();
return (int)cmd.ExecuteScalar();
}
}
Finally, you need to define what you want to happen if there's no match for your WHERE clause. Right now there will be an exception, but that's also true for the original code in the question, so as far as I know at this time that's what you actually want to do.
try
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT USER_ID from tblUser where USERNAME =#username";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 30).Value = username;
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
int locaid = Convert.ToInt32(reader.GetOrdinal("USER_ID"));
}
}
}
OR
int locaid = (int) cmd.ExecuteScalar();

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();
}

Iam not able to retrieve completely the data from sql?

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;
}

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).

Subsonic 3 and Activerecord isn't generating MySQL Stored Procedures

It seems that the included T4 templates (or the one in the SVN trunk for that matter) just skips generating SPs for MySQL...
When running StoredProcedures.ttinclude together with MySQL.ttinclude, I get the error "Compiling transformation: The name 'GetSPs' does not exist in the current context".
GetSPs is defined for SQLServer and I saw that someone wrote his own for Oracle, but does anyone have a clue how the proper GetSPs()-method should look like for MySQL?
Personally I don't think it's really functional unless I can run my own SPs :/
I tinkered around a bit with the code from version 2 and came up with a little code (probably not 100% in all situations) that did the trick for me. Put this in MySQL.ttinclude to get Stored Procedures generated. Enjoy!
string[] GetSPList()
{
var result=new List();
const string sql = "SELECT routine_name FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = ?databaseName";
StringBuilder sList = new StringBuilder();
using(conn=new MySqlConnection(ConnectionString))
{
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("?databaseName", DatabaseName);
conn.Open();
using(IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
bool isFirst = true;
while(rdr.Read())
{
if(!isFirst)
sList.Append('|');
isFirst = false;
sList.Append(rdr[0]);
}
rdr.Close();
}
}
return sList.ToString().Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
}
List GetSPParams(string spName)
{
var result=new List();
MySqlCommand cmd = new MySqlCommand();
using(conn=new MySqlConnection(ConnectionString))
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = spName;
cmd.CommandType = CommandType.StoredProcedure;
try
{
MySqlCommandBuilder.DeriveParameters(cmd);
}
catch
{
}
if(cmd.Parameters.Count > 0)
{
foreach(MySqlParameter param in cmd.Parameters)
{
SPParam p = new SPParam();
p.SysType = GetSysType(param.MySqlDbType.ToString());
p.DbType = param.DbType.ToString();
p.Name = param.ParameterName;
p.CleanName=CleanUp(p.Name);
result.Add(p);
}
}
conn.Close();
}
return result;
}
List GetSPs(){
var result=new List();
string[] spNames = GetSPList();
foreach(string spName in spNames){
var sp=new SP();
sp.Name=spName;
sp.CleanName=CleanUp(sp.Name);
sp.Parameters=GetSPParams(sp.Name);
result.Add(sp);
}
return result;
}
I got this code to run by adding it to my MySQL.ttinclude however I had to change the generic List's to typed lists. eg: List<SPParam> and List<SP>. The code worked after that though ;-)
As per craig's answer, I changed the Lists to typed lists and I also needed to remove var result=new List(); from the GetSPList() code block. Cheers