MySQL - Retriving Data from database

Asked By Nami123
08-Sep-11 01:07 AM

Hello,
     I have a table with 2 columns one is Timestamp and the other one is ID.Sir what i need is to check whether there is any  IDs present before and after any particular timestamp , if present i need to get the Id immediatly before that Timestamp. can anybody tell me the respective queries

Thanks&Regards
Nami
  Web Star replied to Nami123
08-Sep-11 01:14 AM

MySQL Stored Procedures

A stored procedure is made up of one or more SQL statements or commands and is stored within the database. Stored procedures can be used to perform any type of database operation such as retrieving one or more rows, inserting, updating, deleting data, or perhaps multiple database operations at once.

Before moving on, let’s take a look at creating a stored procedure. Launch MySQL Query Browser, connect to yourversedbdatabase, open a new Script Tab, and execute the following script.

DELIMITER $$

DROP PROCEDURE IF EXISTS `versedb`.`usp_Verse_GetList`$$
CREATE PROCEDURE `usp_Verse_GetList`()
BEGIN
  SELECT  verse_id,
      verse_text,
      verse_ref
  FROM  verse
  ORDER BY
      verse_ref DESC;
END$$

DELIMITER ;
 
This simple stored procedure retrieves all the rows in the verse table ordered by verse reference in descending order. To see this stored procedure in action, open a new Query Tab and execute the following command.
 
CALL usp_Verse_GetList();
 
What you should see (assuming you have data in yourversetable from Part 1), is a list of all the rows in your table ordered by the verse reference in descending order, just as you might expect.

One of the primary benefits of using stored procedures is that SQL statements and logic can be maintained apart from the applications that use them. So, instead of embedding SQL commands in your application, your application only needs to know how to execute the stored procedures it needs.

Stored procedures also support parameters. In this way, a single stored procedure can be used in many scenarios without having to be modified. For example, you can create a stored procedure that can retrieve a single row in your table based upon a primary key value passed as a parameter.

DELIMITER $$

DROP PROCEDURE IF EXISTS `versedb`.`usp_Verse_Get_By_Id`$$
CREATE PROCEDURE `usp_Verse_Get_By_Id`(v_id INT)
BEGIN
  SELECT  verse_id,
      verse_text,
      verse_ref
  FROM    verse
  WHERE   verse_id = v_id;
END$$
 
To see the stored procedure in action, execute the following command.
 
CALL usp_Verse_Get_By_Id(2);
 
What you should see is a single row returned from the database where theverse_idfield is equal to 2. To retrieve a different row, you would simply replace the value 2 with a different valid primary key value. If you specify a value that does not exist in the table, then no rows would be returned.

A couple more things to mention: it is possible to define output parameters as well as for input, and stored procedures do not have to return any rows. We will look at an example of both in a later article, but imagine the scenario of creating a stored procedure to insert a new row into a table. You might pass the values for the row as input parameters, return the new primary key ID assigned to the inserted row as an output parameter, and would not need to return any rows of data.

Calling MySQL Stored Procedures from ASP.NET

Executing a stored procedure using ASP.NET is nearly identical to executing straight SQL. Unless a procedure requires parameters, you only need to provide the name of the stored procedure in the command text, and specify theCommandTypeproperty is of typeStoredProcedure.

// Get the MySQL connection string stored in the Web.config
string cnnString = ConfigurationSettings.AppSettings["ConnectionString"];

// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(cnnString);
MySqlDataAdapter adapter = new MySqlDataAdapter();

// Create a SQL command object
string cmdText = "usp_Verse_GetList";
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);

// Set the command type to StoredProcedure
cmd.CommandType = CommandType.StoredProcedure;

// Create and fill a DataSet
DataSet ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
 
One difference you might notice from the previous article is retrieving the connection string from the web.config usingConfigurationSettings.AppSettings, which is typically best practice. If you are not familiar with this technique, you would simply create anblock in your web.config that looks like the following.
 
<appsettings>
  <add key="ConnectionString" value="Server=localhost;Port=3306;Database=versedb;Uid=root;Pwd=mySecret" />
  </add>
</appsettings>
 
You would need to add thesection directly afterand before. If you already have ansection defined, you only need to insert thenode for the connection string.

Executing Stored Procedures with Parameters

To execute a stored procedure with parameters, you must create and add aMySqlParameterobject to theMySqlCommand.Parameterscollection for each required parameter.  Also, parameter names in MySQL use a prefix of "?" which is similar to Microsoft SQL Server's use of "@."

// Hard-coding the Verse ID for example only
int verseID = 2;

// ...Code to create connection goes here...

// Create a SQL command object
string cmdText = "usp_Verse_Get_By_Id";
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);

// Set the command type to StoredProcedure
cmd.CommandType = CommandType.StoredProcedure;

// Create the verse ID parameter
MySqlParameter param;
param = new MySqlParameter("?v_id", MySqlDbType.Int32);
param.Value = verseID;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);

// ...Code to build DataSet goes here...
 
Of course, you would probably wrap all of this code in a method that takes a verseID as a parameter and returns aDataSetorDataRow.

Summary

In summary, you might think of stored procedures as a public method exposed by your database that encapsulates your SQL code. You can make any change to the stored procedure’s code, and as long as the name of the procedure and its parameters, if any, do not change (in other words, the “method signature” to continue our illustration), there would be no need to modify your ASP.NET application.
 
Hopefully this gives you a starting point for using MySQL stored procedures.  However, we have only begun to scratch the surface of this very powerful feature.  In the future, we will look at creating more complex stored procedures, and using stored procedures to insert, update, and delete data in your database.
  James H replied to Nami123
08-Sep-11 01:23 AM
Hi Please see this code snippet to connect to the MYSQL
using
System;
using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.ComponentModel;
 
[DataObject(true)]
public static class MessagesDB
{
  private static string GetConnectionString()
  {
    return ConfigurationManager.ConnectionStrings
    ["MySQLConnectionString"].ConnectionString;
  }
 
  [DataObjectMethod(DataObjectMethodType.Select)]
  public static List<MessageItem> GetMessages()
  {
    MySqlCommand cmd = new MySqlCommand("ShowAll",
               new MySqlConnection(GetConnectionString()));
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection.Open();
    MySqlDataReader dr =
       cmd.ExecuteReader(CommandBehavior.CloseConnection);
 
    List<MessageItem> MessageItemlist = new List<MessageItem>();
    while (dr.Read())
    {
      MessageItem MessageItem = new MessageItem();
      MessageItem.Entry_ID = Convert.ToInt32(dr["Entry_ID"]);
      MessageItem.Message = Convert.ToString(dr["Message"]);
      MessageItem.Name = Convert.ToString(dr["Name"]);
      MessageItem.Email = Convert.ToString(dr["Email"]);
      MessageItemlist.Add(MessageItem);
    }
    dr.Close();
    return MessageItemlist;
  }
 
  [DataObjectMethod(DataObjectMethodType.Insert)]
  public static void InsertMessage(MessageItem MessageItem)
  {
    MySqlCommand cmd = new MySqlCommand("InsertMessage",
               new MySqlConnection(GetConnectionString()));
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new MySqlParameter("param1", MessageItem.Name));
    cmd.Parameters.Add(new MySqlParameter("param2", MessageItem.Email));
    cmd.Parameters.Add(new MySqlParameter("param3", MessageItem.Message));
    cmd.Connection.Open();
    cmd.ExecuteNonQuery();
    cmd.Connection.Close();
  }
 
  [DataObjectMethod(DataObjectMethodType.Update)]
  public static int UpdateMessage(MessageItem MessageItem)
  {
    MySqlCommand cmd = new MySqlCommand("UpdateMessage",
               new MySqlConnection(GetConnectionString()));
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new MySqlParameter("paramkey", MessageItem.Entry_ID));
    cmd.Parameters.Add(new MySqlParameter("param1", MessageItem.Name));
    cmd.Parameters.Add(new MySqlParameter("param2", MessageItem.Email));
    cmd.Parameters.Add(new MySqlParameter("param3", MessageItem.Message));
    cmd.Connection.Open();
    int i = cmd.ExecuteNonQuery();
    cmd.Connection.Close();
    return i;
  }
 
  [DataObjectMethod(DataObjectMethodType.Delete)]
  public static int DeleteMessage(MessageItem MessageItem)
  {
    MySqlCommand cmd = new MySqlCommand("DeleteMessage",
        new MySqlConnection(GetConnectionString()));
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new MySqlParameter("param1", MessageItem.Entry_ID));
    cmd.Connection.Open();
    int i = cmd.ExecuteNonQuery();
    cmd.Connection.Close();
    return i;
  }
Create New Account
help
ms sql & mysql SQL Server can i run both on the same server? SQL Server Discussions SQL Server (1) MySQL (1) SQL Server Books Online (1) Microsoft sql (1) Online (1) Mindspring
Compound INSERT SELECT FROM WHERE subquery problem MySQL -> SQL Server 2005 conversion SQL Server , SQL, Server, 2005, conversion" / > This SQL language is nuts, just nuts. How does anybody put up with such a crude scripting
SQL Server SQL Server Security Discussions SQL Server (1) Role (1) Privileges (1) Database (1) Hi, The following excerpt is taken from Chapter 5 - Microsoft SQL Server 2000 Security of Microsoft SQL Server 2000 Administrator's Pocket Consultant (ISBN 0-7356-1129
What's the go with sql server SQL Server I was just saying today that sql server is full of silly limitations and I seem to hit on a new one every features with more ways to manipulate things than you can poke a stick at. In sql server we don't even have a full range of date functions (a pretty basic feature
SQL Server Migration Assistant Wizard for ACCESS - can't connect to SQL Server SQL Server Hello - - The Wizard leads me through finding and adding the mdb files, and then shows the following error in the step "Connect to SQL Server 2005": an instance of SQL Server 2005." Relevant information about my SQL Server 2005 version