Search Results

Search found 25 results on 1 pages for 'mysqldatareader'.

Page 1/1 | 1 

  • SubSonic: MySqlDataReader closes connection.

    - by SchlaWiener
    I am using SubSonic 2.1 and entcountered a problem while executing a Transaction with SharedDbConnectionScope and TransactionScope. The problem is that in the obj.Save() method I get an "The connection must be valid and open" exception I tracked down the problem to this line: // Loads a SubSonic ActiveRecord object User user = new User(User.Columns.Username, "John Doe"); in this Constructor of the User class a method "LoadParam" is called which eventually does if (rdr != null) rdr.Close(); It looks like the rdr.Close() implicitly closes my connection which is fine when using the AutomaticConnection. But during a transaction it is usally not a good idea to close the connection :-) My Question is if this is by design or if it's an error in the MySqlDataReader.

    Read the article

  • MySqlDataReader giving error at build

    - by TuxMeister
    Hey there. I have a function in VB.net that authenticates a user towards a MySQL DB before launching the main application. Here's the code of the function: Public Function authConnect() As Boolean Dim dbserver As String Dim dbuser As String Dim dbpass As String dbserver = My.Settings.dbserver.ToString dbuser = My.Settings.dbuser.ToString dbpass = My.Settings.dbpass.ToString conn = New MySqlConnection myConnString = "server=" & dbserver & ";" & "user id=" & dbuser & ";" & "password=" & dbpass & ";" & "database=rtadmin" Dim myCommand As New MySqlCommand Dim myAdapter As New MySqlDataAdapter Dim myData As New DataTable Dim myDataReader As New MySqlDataReader Dim query As String myCommand.Parameters.Add(New MySqlParameter("?Username", login_usr_txt.Text)) myCommand.Parameters.Add(New MySqlParameter("?Password", login_pass_txt.Text)) query = "select * from users where user = ?Username and passwd = ?Password" conn.ConnectionString = myConnString Try conn.Open() Try myCommand.Connection = conn myCommand.CommandText = query myAdapter.SelectCommand = myCommand myDataReader = myCommand.ExecuteReader If myDataReader.HasRows() Then MessageBox.Show("You've been logged in.", "RT Live! Information", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Catch ex As Exception End Try Catch ex As Exception End Try End Function The function is not yet complete, there are a few other things that need to be done before launching the application, since I'm using a MessageBox to display the result of the login attempt. The error that I'm getting is the following: Error 1 'MySql.Data.MySqlClient.MySqlDataReader.Friend Sub New(cmd As MySql.Data.MySqlClient.MySqlCommand, statement As MySql.Data.MySqlClient.PreparableStatement, behavior As System.Data.CommandBehavior)' is not accessible in this context because it is 'Friend'. C:\Users\Mario\documents\visual studio 2010\Projects\Remote Techs Live!\Remote Techs Live!\Login.vb 43 13 Remote Techs Live! Any ideas? Thanks.

    Read the article

  • MySqlDataAdapter or MySqlDataReader for bulk transfer?

    - by Jeff Meatball Yang
    I'm using the MySql connector for .NET to copy data from MySql servers to SQL Server 2008. Has anyone experienced better performance using one of the following, versus the other? DataAdapter and calling Fill to a DataTable in chunks of 500 DataReader.Read to a DataTable in a loop of 500 I am then using SqlBulkCopy to load the 500 DataTable rows, then continue looping until the MySql record set is completely transferred. I am primarily concerned with using a reasonable amount of memory and completing in a short amount of time. Any help would be appreciated!

    Read the article

  • mysql data read returning 0 rows from class

    - by Neo
    I am implementing a database manager class within my app, mainly because there are 3 databases to connect to one being a local one. However the return function isn't working, I know the query brings back rows but when it is returned by the class it has 0. What am I missing? public MySqlDataReader localfetchrows(string query, List<MySqlParameter> dbparams = null) { using (var conn = connectLocal()) { Console.WriteLine("Connecting local : " + conn.ServerVersion); MySqlCommand sql = conn.CreateCommand(); sql.CommandText = query; if (dbparams != null) { if (dbparams.Count > 0) { sql.Parameters.AddRange(dbparams.ToArray()); } } MySqlDataReader reader = sql.ExecuteReader(); Console.WriteLine("Reading data : " + reader.HasRows + reader.FieldCount); return reader; /* using (MySqlCommand sql = conn.CreateCommand()) { sql.CommandText = query; if (dbparams != null) { if (dbparams.Count > 0) { sql.Parameters.AddRange(dbparams.ToArray()); } } MySqlDataReader reader = sql.ExecuteReader(); Console.WriteLine("Reading data : " + reader.HasRows + reader.FieldCount); sql.Parameters.Clear(); return reader; }*/ } } And the code to get the results query = @"SELECT jobtypeid, title FROM jobtypes WHERE active = 'Y' ORDER BY title ASC"; //parentfrm.jobtypes = db.localfetchrows(query); var rows = db.localfetchrows(query); Console.WriteLine("Reading data : " + rows.HasRows + rows.FieldCount); while (rows.Read()){ } These scripts return the following : Connecting local : 5.5.16 Reading data : True2 Reading data : False0

    Read the article

  • ASP.NET Membership ChangePassword control - Need to check for previous password

    - by Steve
    Hi guys, I have a new table that hold old passwords, I need to check if there is a match. If there is a match I need the ChangePassword contol to NOT change the password. I need to tell the user that this password was used and pic a new one. I can't seem to be able to interrupt the control from changing the password. Maybe I am using the wrong event. Here is a piece of my code, or how I wish it would work. I appreciate all your help. protected void ChangePassword1_ChangedPassword(object sender, EventArgs e) { MembershipUser user = Membership.GetUser(); string usrName = ""; if (user != null) { string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString; SqlConnection mySqlConnection = new SqlConnection(connStr); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "Select UserName from OldPasswords where UserName = 'test'"; mySqlConnection.Open(); SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader(CommandBehavior.Default); while (mySqlDataReader.Read()) { usrName = mySqlDataReader["UserName"].ToString(); if (usrName == user.ToString()) { Label1.Text = "Match"; } else { Label1.Text = "NO Match!"; } }

    Read the article

  • Contradictory MySqlReader errors

    - by Lazlo
    MySqlCommand command = connection.CreateCommand(); command.CommandText = string.Format("SELECT * FROM characters WHERE account_id = '{0}'", this.ID); MySqlDataReader reader = command.ExecuteReader(); while (filler.Reader.Read()) { ... } I get an error at the last line saying "Invalid attempt to Read when reader is closed." Now, if I add another line before it, as in: MySqlCommand command = connection.CreateCommand(); command.CommandText = string.Format("SELECT * FROM characters WHERE account_id = '{0}'", this.ID); MySqlDataReader reader = command.ExecuteReader(); reader = command.ExecuteReader(); // Here. while (filler.Reader.Read()) { ... } I get an error at that new line saying "There is already an open DataReader associated with this Connection which must be closed first." Alright, I don't want to get picky here, but is my reader open or closed?

    Read the article

  • C#/.Net Error: MySql.Data Object reference not set to an instance of an object.

    - by Simon
    Hello, I get this exception on my Windows 7 64bit in application running in VS 2008 express. I am using Connector/Net 6.2.2.0: Message: Object reference not set to an instance of an object. Source: MySql.Data in MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int32& insertedId) Stack trace: in MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int32& insertedId) in MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId) in MySql.Data.MySqlClient.MySqlDataReader.NextResult() in MySql.Data.MySqlClient.MySqlDataReader.Close() in MySql.Data.MySqlClient.MySqlConnection.Close() in MySql.Data.MySqlClient.MySqlConnection.Dispose(Boolean disposing) in System.ComponentModel.Component.Finalize() No inner exception. This exception is unhalted and the debugger dont point on any code line. It just say "Object reference not set to an instance of an object. MySql.Data" This error is really hard to repeat. On my Windows XP 32bit is all ok. Could it be error in 64bit Windows 7? Thank you very much for your answers. Regards, simon

    Read the article

  • Getting MySQL record count with C#

    - by she hates me
    Hello, I would like to know how can I get record count of a query with C#. Here is the code that I use.. MySqlDataReader recordset = null; query = new MySqlCommand("SELECT * FROM test ORDER BY type_ID ASC", this.conn); recordset = query.ExecuteReader(); while (recordset.Read()) { result.Add(recordset["type_ID"].ToString()); } return result;

    Read the article

  • How can I modify my classes to use it's collections in WPF TreeView

    - by Victor
    Hello, i'am trying to modify my objects to make hierarchical collection model. I need help. My objects are Good and GoodCategory: public class Good { int _ID; int _GoodCategory; string _GoodtName; public int ID { get { return _ID; } } public int GoodCategory { get { return _GoodCategory; } set { _GoodCategory = value; } } public string GoodName { get { return _GoodName; } set { _GoodName = value; } } public Good(IDataRecord record) { _ID = (int)record["ID"]; _GoodtCategory = (int)record["GoodCategory"]; } } public class GoodCategory { int _ID; string _CategoryName; public int ID { get { return _ID; } } public string CategoryName { get { return _CategoryName; } set { _CategoryName = value; } } public GoodCategory(IDataRecord record) { _ID = (int)record["ID"]; _CategoryName = (string)record["CategoryName"]; } } And I have two Collections of these objects: public class GoodsList : ObservableCollection<Good> { public GoodsList() { string goodQuery = @"SELECT `ID`, `ProductCategory`, `ProductName`, `ProductFullName` FROM `products`;"; using (MySqlConnection conn = ConnectToDatabase.OpenDatabase()) { if (conn != null) { MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = productQuery; MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Add(new Good(rdr)); } } } } } public class GoodCategoryList : ObservableCollection<GoodCategory> { public GoodCategoryList () { string goodQuery = @"SELECT `ID`, `CategoryName` FROM `product_categoryes`;"; using (MySqlConnection conn = ConnectToDatabase.OpenDatabase()) { if (conn != null) { MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = productQuery; MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Add(new GoodCategory(rdr)); } } } } } So I have two collections which takes data from the database. But I want to use thats collections in the WPF TreeView with HierarchicalDataTemplate. I saw many post's with examples of Hierarlichal Objects, but I steel don't know how to make my objects hierarchicaly. Please help.

    Read the article

  • Invalid attempt to access a field before calling Read() INSERT

    - by Raphael Fernandes
    I'm trying to use this code to check if the system already exists a field with this value Dim adap As New MySqlDataAdapter Dim sqlquery = "SELECT * FROM client WHERE code ='"+ TxtCode.Text +"'" Dim comand As New MySqlCommand() comand.Connection = con comand.CommandText = sqlquery adap.SelectCommand = comand Dim data As MySqlDataReader data = comando2.ExecuteReader() leitor.Read() If (data(3).ToString) = code Then MsgBox("already exists", MsgBoxStyle.Information) TxtCode.ResetText() TxtCode.Focus() Else Console.WriteLine(insert("INSERT INTO client (name, tel, code) VALUES ('" & name & "', '" & tel & "')")) con.Close() End If

    Read the article

  • Visual Studio 2010 Hosting :: Connect to MySQL Database from Visual Studio VS2010

    - by mbridge
    So, in order to connect to a MySql database from VS2010 you need to 1. download the latest version of the MySql Connector/NET from http://www.mysql.com/downloads/connector/net/ 2. install the connector (if you have an older version you need to remove it from Control Panel -> Add / Remove Programs) 3. open Visual Studio 2010 4. open Server Explorer Window (View -> Server Explorer) 5. use Connect to Database button 6. in the Choose Data Source windows select MySql Database and press Continue 7. in the Add Connection window - set server name: 127.0.0.1 or localhost for MySql server running on local machine or an IP address for a remote server - username and password - if the the above data is correct and the connection can be made, you have the possibility to select the database If you want to connect to a MySql database from a C# application (Windows or Web) you can use the next sequence: //define the connection reference and initialize it MySql.Data.MySqlClient.MySqlConnection msqlConnection = null; msqlConnection = new MySql.Data.MySqlClient.MySqlConnection(“server=localhost;user id=UserName;Password=UserPassword;database=DatabaseName;persist security info=False”);     //define the command reference MySql.Data.MySqlClient.MySqlCommand msqlCommand = new MySql.Data.MySqlClient.MySqlCommand();     //define the connection used by the command object msqlCommand.Connection = this.msqlConnection;     //define the command text msqlCommand.CommandText = "SELECT * FROM TestTable;"; try {     //open the connection     this.msqlConnection.Open();     //use a DataReader to process each record     MySql.Data.MySqlClient.MySqlDataReader msqlReader = msqlCommand.ExecuteReader();     while (msqlReader.Read())     {         //do something with each record     } } catch (Exception er) {     //do something with the exception } finally {     //always close the connection     this.msqlConnection.Close(); }.

    Read the article

  • Read from multiple tables in vb.net data reader

    - by user225269
    I'm trying to read from two tables in mysql: Dim sqlcom As MySqlCommand = New MySqlCommand("Select * from mother, father where IDNO= '" & TextBox14.Text & "' ", sqlcon) -But I get this error: Column 'IDNO' in where clause is ambiguous Here is the whole code: Dim NoAcc As String Dim NoAccmod2 As String Dim NoPas As String Dim sqlcon As New MySqlConnection("Server=localhost; Database=school;Uid=root;Pwd=nitoryolai123$%^;") Dim sqlcom As MySqlCommand = New MySqlCommand("Select * from mother, father where IDNO= '" & TextBox14.Text & "' ", sqlcon) sqlcon.Open() Dim rdr As MySqlDataReader rdr = sqlcom.ExecuteReader If rdr.HasRows Then rdr.Read() NoAcc = rdr("IDNO") If (TextBox14.Text = NoAcc) Then TextBox7.Text = rdr("MOTHER") If (TextBox14.Text = NoAcc) Then TextBox8.Text = rdr("MOTHER_OCCUPATION") If (TextBox14.Text = NoAcc) Then TextBox10.Text = rdr("FATHER") If (TextBox14.Text = NoAcc) Then TextBox11.Text = rdr("FATHER_OCCUPATION") End If -Any suggestions that could help solve this problem? Or even other techniques on achieving the goal of reading data from two tables using data reader? This is a winform, not a web form

    Read the article

  • Problems refreshing DataGridView after database update in VB.NET

    - by Gbolahan
    Dim myQuery = "UPDATE table1 SET data= CONCAT (data,'" & vbCrLf & "[ " & Date.Now() & " ]" & " " & "[" & getCN() & "]" & " " & txtTelenotes.Text & "[ item1 ]" & "') WHERE id='" & txtID.Text & "'" myCommand.Connection = conn myCommand.CommandText = myQuery myAdapter.SelectCommand = myCommand Dim myData As MySqlDataReader myData = myCommand.ExecuteReader() txtTelenotes.Text = "" dgvREcord.Refresh() I tried refreshing the DataGridView using: dgvREcord.Refresh() but it does not load the changes from the database.

    Read the article

  • C# mysqlreader on same connection error

    - by dominiquel
    Hi, I must find a way to do this in C#, if possible... I must loop on my folder list (mysql table), and for each folder I instanciate I must do another query, but when I do this it says : "There is already an open DataReader associated with this Connection" and I am inside a mysqlreader loop already. Note that I have oversimplified the code just to show you, the fact is that I must do queries inside a mysqlreader loop, and it looks to be impossible as they are on the same connection? MySqlConnection cnx = new MySqlConnection(connexionString); cnx.Open(); MySqlCommand command= new MySqlCommand("SELECT * FROM folder WHERE folder_id = " + id, cnx); MySqlDataReader reader= commande.ExecuteReader(); while (reader.Read()) { this.folderList[this.folderList.Length] = new CFolder(reader.GetInt32"folder_id"), cnx); } reader.Close(); cnx.Close();

    Read the article

  • referesh datagridview after database update in vb.net

    - by Gbolahan
    Dim myQuery = "UPDATE table1 SET data= CONCAT (data,'" & vbCrLf & "[ " & Date.Now() & " ]" & " " & "[" & getCN() & "]" & " " & txtTelenotes.Text & "[ item1 ]" & "') WHERE id='" & txtID.Text & "'" myCommand.Connection = conn myCommand.CommandText = myQuery myAdapter.SelectCommand = myCommand Dim myData As MySqlDataReader myData = myCommand.ExecuteReader() txtTelenotes.Text = "" dgvREcord.Refresh() tried refreshing the datagridview using dgvREcord.Refresh() but it does not load the changes form the database. Any help Pls.. Thanks.

    Read the article

  • Is passing a Command object/Reader to a function a good idea?

    - by Cyril Gupta
    I've been getting some inexplicable errors (running out of connections from the connection pool) with MySql database with .Net 4 (C#). Till now all my attempts at finding a reason for this have been in vain. Now I also have a situation in which a lock on a table is not cleared for a long time even though all I have been doing is read operations from it. My code looks okay (I've put all readers and connections in using blocks). The only anomaly I have is that I've been passing MySqlCommand and MySqlDataReader objects as parameters to functions who work with them. That doesn't seem like a bad idea for me because it avoids some repetition (DRY!). But since I can't find any other explanation I have to suspect that this is causing the problem. What do you think?

    Read the article

  • Table character encoding - exception in application

    - by zgnilec
    I have a code: CREATE TABLE IF NOT EXISTS Person ( name varchar(24) ... ) CHARACTER SET utf8 COLLATE utf8_polish_ci; This works OK in my application, but I read if someone put in name field a string that contains character wchich code is greater than 127, database will use 2 bytes (or more) to store this character. So i think, i will change character set to utf16: CHARACTER SET utf16 COLLATE utf16_polish_ci; But now when I run my application, exception apears: KeyNotFoundException. It apears exactly at these instructions: MySqlCommand komenda = baza.Polaczenie.CreateCommand (); komenda.CommandText = zapytanie; MySqlDataReader dr = komenda.ExecuteReader (); // HERE, at execute reader method if (dr.Read ()) ... 1) Anyone had similar problem? 2) Any idea how to use always 2 bytes/char in database field?

    Read the article

  • having trouble disabling textbox in vb.net

    - by user225269
    How do I disable a textbox the second time? here is my code, In form load the textbox is disabled, unless the user will input an idnumber that is in the database. But what if the user will input an idnumber that is in the database then, input again another that is not, That is where this code comes in, but it has problems, it doesnt disable the textbox in the event of a mouse click, what would be the proper way of doing this? Private Sub Button12_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button12.MouseClick Dim NoAcc As String Dim NoAccmod2 As String Dim NoPas As String Dim sqlcon As New MySqlConnection("Server=localhost; Database=school;Uid=root;Pwd=nitoryolai123$%^;") Dim sqlcom As MySqlCommand = New MySqlCommand("Select * from student where IDNO= '" & TextBox14.Text & "' ", sqlcon) sqlcon.Open() Dim rdr As MySqlDataReader rdr = sqlcom.ExecuteReader If rdr.HasRows Then rdr.Read() NoAcc = rdr("IDNO") If (TextBox14.Text <> NoAcc) Then MsgBox("ID Number is not yet registered!, please register first in the general information before trying to register parents information", MsgBoxStyle.Information) TextBox7.Enabled = False TextBox8.Enabled = False TextBox9.Enabled = False TextBox10.Enabled = False TextBox11.Enabled = False TextBox12.Enabled = False TextBox13.Enabled = False End If End If

    Read the article

  • Why is F# member not found when used in subclass

    - by James Black
    I have a base type that I want to inherit from, for all my DAO objects, but this member gets the error further down about not being defined: type BaseDAO() = member v.ExecNonQuery2(conn)(sqlStr) = let comm = new MySqlCommand(sqlStr, conn, CommandTimeout = 10) comm.ExecuteNonQuery |> ignore comm.Dispose |> ignore I inherit in this type: type CreateDatabase() = inherit BaseDAO() member private self.createDatabase(conn) = self.ExecNonQuery2 conn "DROP DATABASE IF EXISTS restaurant" This is what I see when my script runs in the interactive shell: --> Referenced 'C:\Program Files\MySQL\MySQL Connector Net 6.2.3\Assemblies\MySql.Data.dll' [Loading C:\Users\jblack\Documents\Visual Studio 2010\Projects\RestaurantService\RestaurantDAO\BaseDAO.fs] namespace FSI_0106.RestaurantServiceDAO type BaseDAO = class new : unit -> BaseDAO member ExecNonQuery2 : conn:MySql.Data.MySqlClient.MySqlConnection -> sqlStr:string -> unit member execNonQuery : sqlStr:string -> unit member execQuery : sqlStr:string * selectFunc:(MySql.Data.MySqlClient.MySqlDataReader -> 'a list) -> 'a list member f : x:obj -> string member Conn : MySql.Data.MySqlClient.MySqlConnection end [Loading C:\Users\jblack\Documents\Visual Studio 2010\Projects\RestaurantService\RestaurantDAO\CreateDatabase.fs] C:\Users\jblack\Documents\Visual Studio 2010\Projects\RestaurantService\RestaurantDAO\CreateDatabase.fs(56,14): error FS0039: The field, constructor or member 'ExecNonQuery2' is not defined I am curious what I am doing wrong. I have tried not inheriting, and just instantiating the BaseDAO type in the function, but I get the same error. I started on this path because I had a property that had the same error, so it seems there may be a problem with how I am defining my BaseDAO type, but it compiles with no error, which further confuses me about this problem.

    Read the article

  • IndexOutOfRangeException when a stream is a multiple of the buffer size

    - by dnord
    I don't have a lot of experience with streams and buffers, but I'm having to do it for a project, and I'm stuck on an exception being thrown when the stream I'm reading is a multiple of the buffer size I've chosen. Let me show you: My code starts by reading bufferSize (100, let's say) bytes from the stream: numberOfBytesRead = DataReader.GetBytes(0, index, output, 0, bufferSize); Then, I loop through a while loop: while (numberOfBytesRead == bufferSize) { BufferWriter.Write(output); BufferWriter.Flush(); index += bufferSize; numberOfBytesRead = DataReader.GetBytes(0, index, output, 0, bufferSize); } ... and, once we get to a non-bufferSize read, we know we've hit the end of the stream and can move on. But if the bufferSize is 100, and the stream is 200, we'll read positions 0-99, 100-199, and then the attempt to read 200-299 errors out. I'd like it if it returned 0, but it throws an error. What I'm doing to handle that is, well, a try-catch: catch (System.IndexOutOfRangeException) numberOfBytesRead = 0; ...which ends the loop, and successfully finishes the thing, but we all know I don't want to control code flow with error handling. Is there a better (more standard?) way to handle stream reading when the stream length is unknown? This seems like a small wrinkle in a fairly reasonable strategy for reading streams, but I just don't know if I've got it wrong or what. The specifics of this (which I've cleaned up a little bit for posting) are a MySqlDataReader hitting a LARGEBLOB column. It's working whenever the buffer is larger than the number of returned bytes, or when the number of returned bytes is not a multiple of bufferSize. Because we don't, in that case, throw an IndexOutOfRangeException.

    Read the article

  • C# WPF Show Image from Mysql

    - by user3718026
    i'm a student and i am bad at programing. I saved the images in my mysql database for each player. I created a program where I can list some soccer players from my database. When i click on a listed player in datagrid, a new window appears with the information about the player. Everything works, but now i want a picture of the selected player to be displayed on the information window from the database. Can anybody help me? My english is not the best (i'm 17) so i hope you can understand what i mean. This is what i tried to do but i don't know how to continue. PS. It's in WPF. MySqlCommand cmd = new MySqlCommand("SELECT Bilder FROM spieler WHERE Bilder='{8}'"); MySqlDataReader rdr1 = cmd.ExecuteReader(); try { conn.Open(); while (rdr1.Read()) { // image1... I don't know what to write here } } catch (Exception ex) { MessageBox.Show("Fehler: " + ex); } rdr1.Close()

    Read the article

  • WPF/C#: How to simplify the use of codes when calling a function (Generating Images)

    - by eibhrum
    I created a function in one of my application that allows to generate an image (in WPF) by getting the 'source path' from the database that I am using: public void ShowImageThumb() { try { cn = new MySqlConnection(); cn.ConnectionString = ConfigurationManager.AppSettings["MyConnection"]; cn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT thumb FROM album WHERE thumbNo=1"; MySqlDataAdapter adp = new MySqlDataAdapter(); adp.SelectCommand = cmd; DataTable dt = new DataTable(); adp.Fill(dt); MySqlDataReader r = cmd.ExecuteReader(); while (r.Read()) { BitmapImage bmi1 = new BitmapImage(new Uri(r[0].ToString(), UriKind.Relative)); image1.Source = bmi1; } r.Close(); cn.Close(); } catch (Exception err){ System.Windows.MessageBox.Show(err.Message); } finally { } } Take a look on my SQL statement. I put a WHERE thumbNo=1 which allows the function to get 1 record. You see, I do have at least 10 records - file paths listed in that table. I just wanna ask if there's a possible way to make my SQL statement something like this: SELECT thumb FROM album; while having this piece of code inserted in my function: BitmapImage bmi2 = new BitmapImage(new Uri(r["second record?"].ToString(), UriKind.Relative)); image2.Source = bmi2; //something like this BitmapImage bmi3 = new BitmapImage(new Uri(r["third record?"].ToString(), UriKind.Relative)); image3.Source = bmi3; //something like this and so on and so forth, without ending up creating 10 different functions for 10 records. ShowImageThumb2(); . . // will not do this . ShowImageThumb10(); Sorry for the lengthy post. I hope somebody could answer back. Thanks!

    Read the article

  • Pulling record from mySQL database only working for userid and not email

    - by user2908467
    This function works because I search by userid: private void showList_Click(object sender, EventArgs e) { int id = 0; for (int i = 0; i <= sqlClient.Count("UserList"); i++) { Dictionary<string, string> dik = sqlClient.Select("UserList", "userid = " + id); var lines = dik.Select(kv => kv.Key + ": " + kv.Value.ToString()); userList.AppendText(string.Join(Environment.NewLine, lines)); userList.AppendText(Environment.NewLine); userList.AppendText("--------------------------------------"); id++; } } This function does not work because I search by email: private void login_Click(object sender, EventArgs e) { string email = lemail.Text; Dictionary<string, string> dik = sqlClient.Select("UserList", "firstname = " + email); var lines = dik.Select(kv => kv.Key + ": " + kv.Value.ToString()); logged.AppendText(string.Join(Environment.NewLine, lines)); } This is the error message I receive when I click on the login button: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@aol.com' at line 1 The email I searched for in the database was "[email protected]" without quotes. I'm lead to believe by the error message the @ sign is causing conflict as I know it is a special character but I am having a hard time figuring out what phrase to search for to help me. Also, here is the function that is being called: public Dictionary<string, string> Select(string table, string WHERE) { //This methods selects from the database, it retrieves data from it. //You must make a dictionary to use this since it both saves the column //and the value. i.e. "age" and "33" so you can easily search for values. //Example: SELECT * FROM names WHERE name='John Smith' // This example would retrieve all data about the entry with the name "John Smith" //Code = Dictionary<string, string> myDictionary = Select("names", "name='John Smith'"); //This code creates a dictionary and fills it with info from the database. string query = "SELECT * FROM " + table + " WHERE " + WHERE + ""; Dictionary<string, string> selectResult = new Dictionary<string, string>(); if (this.Open()) { MySqlCommand cmd = new MySqlCommand(query, conn); MySqlDataReader dataReader = cmd.ExecuteReader(); try { while (dataReader.Read()) { for (int i = 0; i < dataReader.FieldCount; i++) { selectResult.Add(dataReader.GetName(i).ToString(), dataReader.GetValue(i).ToString()); } } dataReader.Close(); } catch { } this.Close(); return selectResult; } else { return selectResult; } } My database table is called "UserList" The fields in order are as follows: userid, email, password, lastname, firstname Any help would be greatly appreciated. This site is amazing!

    Read the article

  • Embedding generic sql queries into c# program

    - by Pooja Balkundi
    Okay referring to my first question code in the main, I want the user to enter employee name at runtime and then i take this name which user has entered and compare it with the e_name of my emp table , if it exists i want to display all information of that employee , how can I achieve this ? using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace ConnectCsharppToMySQL { public class DBConnect { private MySqlConnection connection; private string server; private string database; private string uid; private string password; string name; //Constructor public DBConnect() { Initialize(); } //Initialize values private void Initialize() { server = "localhost"; database = "test"; uid = "root"; password = ""; string connectionString; connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; connection = new MySqlConnection(connectionString); } //open connection to database private bool OpenConnection() { try { connection.Open(); return true; } catch (MySqlException ex) { //When handling errors, you can your application's response based //on the error number. //The two most common error numbers when connecting are as follows: //0: Cannot connect to server. //1045: Invalid user name and/or password. switch (ex.Number) { case 0: MessageBox.Show("Cannot connect to server. Contact administrator"); break; case 1045: MessageBox.Show("Invalid username/password, please try again"); break; } return false; } } //Close connection private bool CloseConnection() { try { connection.Close(); return true; } catch (MySqlException ex) { MessageBox.Show(ex.Message); return false; } } //Insert statement public void Insert() { string query = "INSERT INTO emp (e_name, age) VALUES('Pooja R', '21')"; //open connection if (this.OpenConnection() == true) { //create command and assign the query and connection from the constructor MySqlCommand cmd = new MySqlCommand(query, connection); //Execute command cmd.ExecuteNonQuery(); //close connection this.CloseConnection(); } } //Update statement public void Update() { string query = "UPDATE emp SET e_name='Peachy', age='22' WHERE e_name='Pooja R'"; //Open connection if (this.OpenConnection() == true) { //create mysql command MySqlCommand cmd = new MySqlCommand(); //Assign the query using CommandText cmd.CommandText = query; //Assign the connection using Connection cmd.Connection = connection; //Execute query cmd.ExecuteNonQuery(); //close connection this.CloseConnection(); } } //Select statement public List<string>[] Select() { string query = "SELECT * FROM emp where e_name=(/*I WANT USER ENTERED NAME TO GET INSERTED HERE*/)"; //Create a list to store the result List<string>[] list = new List<string>[3]; list[0] = new List<string>(); list[1] = new List<string>(); list[2] = new List<string>(); //Open connection if (this.OpenConnection() == true) { //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Create a data reader and Execute the command MySqlDataReader dataReader = cmd.ExecuteReader(); //Read the data and store them in the list while (dataReader.Read()) { list[0].Add(dataReader["e_id"] + ""); list[1].Add(dataReader["e_name"] + ""); list[2].Add(dataReader["age"] + ""); } //close Data Reader dataReader.Close(); //close Connection this.CloseConnection(); //return list to be displayed return list; } else { return list; } } public static void Main(String[] args) { DBConnect db1 = new DBConnect(); Console.WriteLine("Initializing"); db1.Initialize(); Console.WriteLine("Search :"); Console.WriteLine("Enter the employee name"); db1.name = Console.ReadLine(); db1.Select(); Console.ReadLine(); } } }

    Read the article

1