Thursday, 25 September 2014

php-redmine-api/Issue.php at master

<?php
namespace Redmine\Api;
/**
* Listing issues, searching, editing and closing your projects issues.
*
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues
* @author Kevin Saliou <kevin at saliou dot name>
*/
class Issue extends AbstractApi
{
const PRIO_LOW = 1;
const PRIO_NORMAL = 2;
const PRIO_HIGH = 3;
const PRIO_URGENT = 4;
const PRIO_IMMEDIATE = 5;
/**
* List issues
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues
* available $params :
* - offset: skip this number of issues in response (optional)
* - limit: number of issues per page (optional)
* - sort: column to sort with. Append :desc to invert the order.
* - project_id: get issues from the project with the given id, where id is either project id or project identifier
* - tracker_id: get issues from the tracker with the given id
* - status_id: get issues with the given status id only. Possible values: open, closed, * to get open and closed issues, status id
* - assigned_to_id: get issues which are assigned to the given user id
* - cf_x: get issues with the given value for custom field with an ID of x. (Custom field must have 'used as a filter' checked.)
* - query_id : id of the previously saved query
*
* @param array $params the additional parameters (cf avaiable $params above)
* @return array list of issues found
*/
public function all(array $params = array())
{
return $this->retrieveAll('/issues.json', $params);
}
/**
* Get extended information about an issue gitven its id
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues#Using-JSON
* available $params :
* include: fetch associated data (optional). Possible values: children, attachments, relations, changesets and journals
*
* @param string $id the issue id
* @param array $params extra associated data
* @return array information about the issue
*/
public function show($id, array $params = array())
{
return $this->get('/issues/'.urlencode($id).'.json?'.http_build_query($params));
}
/**
* Build the XML for an issue
* @param array $params for the new/updated issue data
* @return SimpleXMLElement
*/
private function buildXML(array $params = array())
{
$xml = new SimpleXMLElement('<?xml version="1.0"?><issue></issue>');
foreach ($params as $k => $v) {
if ('custom_fields' === $k && is_array($v)) {
$this->attachCustomFieldXML($xml, $v);
} elseif ('watcher_user_ids' === $k && is_array($v)) {
$watcher_user_ids = $xml->addChild('watcher_user_ids', '');
$watcher_user_ids->addAttribute('type', 'array');
foreach ($v as $watcher) {
$watcher_user_ids->addChild('watcher_user_id', (int) $watcher);
}
} elseif ('uploads' === $k && is_array($v)) {
$uploads_item = $xml->addChild('uploads', '');
$uploads_item->addAttribute('type', 'array');
foreach ($v as $upload) {
$upload_item = $uploads_item->addChild('upload', '');
foreach ($upload as $upload_k => $upload_v) {
$upload_item->addChild($upload_k, $upload_v);
}
}
} else {
$xml->addChild($k, $v);
}
}
return $xml;
}
/**
* Create a new issue given an array of $params
* The issue is assigned to the authenticated user.
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues#Creating-an-issue
*
* @param array $params the new issue data
* @return SimpleXMLElement
*/
public function create(array $params = array())
{
$defaults = array(
'subject' => null,
'description' => null,
// 'project' => null,
// 'category' => null,
// 'status' => null,
// 'tracker' => null,
// 'assigned_to' => null,
// 'author' => null,
'project_id' => null,
'category_id' => null,
'priority_id' => null,
'status_id' => null,
'tracker_id' => null,
'assigned_to_id' => null,
'author_id' => null,
'due_date' => null,
'start_date' => null,
'watcher_user_ids' => null,
);
$params = $this->cleanParams($params);
$params = array_filter(array_merge($defaults, $params));
$xml = $this->buildXML($params);
return $this->post('/issues.xml', $xml->asXML());
// $json = json_encode(array('issue' => $params));
// return $this->post('/issues.json', $json);
}
/**
* Update issue information's by username, repo and issue number. Requires authentication.
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues#Updating-an-issue
*
* @param string $id the issue number
* @param array $params
* @return SimpleXMLElement
*/
public function update($id, array $params)
{
$defaults = array(
'id' => $id,
'subject' => null,
'notes' => null,
// 'project' => null,
// 'category' => null,
// 'status' => null,
// 'tracker' => null,
// 'assigned_to' => null,
// 'author' => null,
'category_id' => null,
'priority_id' => null,
'status_id' => null,
'tracker_id' => null,
'assigned_to_id' => null,
'due_date' => null,
);
$params = $this->cleanParams($params);
$params = array_filter(array_merge($defaults, $params));
$xml = $this->buildXML($params);
return $this->put('/issues/'.$id.'.xml', $xml->asXML());
}
/**
* @param int $id
* @param string $watcher_user_id
* @return void
*/
public function addWatcher($id, $watcher_user_id)
{
return $this->post('/issues/'.$id.'/watchers.xml', '<user_id>'.$watcher_user_id.'</user_id>');
}
/**
* @param int $id
* @param string $watcher_user_id
* @return void
*/
public function removeWatcher($id, $watcher_user_id)
{
return $this->delete('/issues/'.$id.'/watchers/'.$watcher_user_id.'.xml');
}
/**
* @param int $id
* @param string $status
* @return void
*/
public function setIssueStatus($id, $status)
{
$statusId = $this->client->api('issue_status')->getIdByName($status);
return $this->update($id, array(
'status_id' => $statusId
));
}
/**
* @param int $id
* @param string $note
* @return void
*/
public function addNoteToIssue($id, $note)
{
return $this->update($id, array(
'notes' => $note
));
}
/**
* Transforms literal identifiers to integer ids
* @param array $params
* @return array
*/
private function cleanParams(array $params = array())
{
if (isset($params['project'])) {
$params['project_id'] = $this->client->api('project')->getIdByName($params['project']);
unset($params['project']);
if (isset($params['category'])) {
$params['category_id'] = $this->client->api('issue_category')->getIdByName($params['project_id'], $params['category']);
unset($params['category']);
}
}
if (isset($params['status'])) {
$params['status_id'] = $this->client->api('issue_status')->getIdByName($params['status']);
unset($params['status']);
}
if (isset($params['tracker'])) {
$params['tracker_id'] = $this->client->api('tracker')->getIdByName($params['tracker']);
unset($params['tracker']);
}
if (isset($params['assigned_to'])) {
$params['assigned_to_id'] = $this->client->api('user')->getIdByUsername($params['assigned_to']);
unset($params['assigned_to']);
}
if (isset($params['author'])) {
$params['author_id'] = $this->client->api('user')->getIdByUsername($params['author']);
unset($params['author']);
}
return $params;
}
/**
* Attach a file to an issue issue number. Requires authentication.
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues#Updating-an-issue
*
* @param string $id the issue number
* @param array $attachment
* @return bool|string
*/
public function attach($id, array $attachment)
{
$request['issue'] = array(
'id' => $id,
'uploads' => array(
'upload' => $attachment
)
);
return $this->put('/issues/'.$id.'.json', json_encode($request));
}
/**
* Remove a issue by issue number
*
* @param string $id the issue number
*/
public function remove($id)
{
return $this->delete('/issues/'.$id.'.xml');
}
}

Consuming a JSON service with C#



If you like to consume a JSON web service in C# this example might be handy.

You need to know the url (web address) of the web service

You need to understand what the web service will return


You need to know what kind of security the web service accepts (My example uses Basic Authentication)


You need to understand under which context you are consuming the service (My example uses a Proxy server to communicate)


I found a site that automatically generates a class based on the result of the JSON web service at http://json2csharp.com/. This site can generate an class either by you specifying the url to the web service or providing the JSON result from the service you wish to consume.

Lets just assume in the example that my service will return {“variable1″:1,”variable2″:”a return string”}

By definition this means one variable with an int and one with a string.
JSON2CSHARP will return a usable class for me to use in my code;

public class RootObject
{
    public int variable1 { get; set; }
    public string variable2 { get; set; }
}


Lets go ahead and add some more code to consume this now when we have a nice helper class to contain my result.

string url = “http://yourserver/service?someparams=somevalue“;

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

string username = “username”;


string password = “********”;


// Use the CredentialCache so we can attach the authentication to the request
CredentialCache mycache = new CredentialCache();


// We want to use Basic Authentication
mycache.Add(new Uri(url), “Basic”, new NetworkCredential(username, password));


wr.Credentials = mycache;
wr.Headers.Add(“Authorization”, “Basic ” + Convert.ToBase64String(new ASCIIEncoding().GetBytes(username + “:” + password)));


// Proxy (if you do not need it – ommit it)
wr.Proxy = new WebProxy(http://proxyserver:8080);


// Get the response from the web service
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Stream r_stream = response.GetResponseStream();


//convert it
StreamReader response_stream = new StreamReader(r_stream, System.Text.Encoding.GetEncoding(“utf-8″));

string jSon = response_stream.ReadToEnd();

//clean up your stream
response_stream.Close();

System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

 RootObject result = jsSerializer.Deserialize<RootObject>(jSon);

How do I use the Redmine REST API over https from .net?

 

  Best way to use Redmine REST API over https from .net?

 

  protected void Page_Load(object sender, EventArgs e)
        {

            string host = ConfigurationManager.AppSettings["redmineHost"].ToString();

            string key = ConfigurationManager.AppSettings["redmineKey"].ToString();           

            //  var manager = new RedmineManager(host, user,pass);
            var manager = new RedmineManager(host,
key);
            string str= ReadIssue(host,
key);
            Response.Write(str);
         }

      

    public string ReadIssue (string host,string key)
    {
       ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => true;

            var request = (HttpWebRequest)WebRequest.Create(host+"/issues/1083.json?key="+key+"");
            request.CookieContainer = new CookieContainer();
            request.Method = "GET";
            request.ContentType = "application/json";
           
            using (var response = request.GetResponse()) // Hangs here
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
   
    }

Create Issue using the REST API of Redmine with .NET

Redmine .NET API library is a FREE third-party C# library that can be used to access the Redmine API. It is released under Apache 2 open-source license.


Sample usage:


using System;
using System.Collections.Specialized;
using Redmine.Net.Api;
using Redmine.Net.Api.Types;

namespace RedmineTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string host = "";
            string apiKey = "";

            var manager = new RedmineManager(host, apiKey);

            var parameters = new NameValueCollection {{"status_id", "*"}};
            foreach (var issue in manager.GetObjectList<Issue>(parameters))
            {
                Console.WriteLine("#{0}: {1}", issue.Id, issue.Subject);
            }

            //Create a issue.
            var newIssue = new Issue { Subject = "test", Project = new IdentifiableName{Id =  1}};
            manager.CreateObject(newIssue);

        }
    }
}

Wednesday, 24 September 2014

Updating an object of type T using Redmine

When trying to update an object with invalid or missing attribute parameters, you will get RedmineException that contains the corresponding error messages.

Example:

using System;
using System.Collections.Specialized;
using Redmine.Net.Api;
using Redmine.Net.Api.Types;
namespace RedmineTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string host = "";
            string apiKey = "";

            var manager = new RedmineManager(host, apiKey);

            var issue = manager.GetObject<Issue>("1", null);
            issue.Description = "Updated description"; 

            manager.UpdateObject(issue);

        }
    }
}

Thursday, 18 September 2014

MySQL Linked Server on SQL Server 2008

Introduction

MS SQL servers always provided remote access to servers through RPC mechanisms, but they had the limitation of being confined to invoking procedures on remote locations. A linked server (a virtual server) may be considered a more flexible way of achieving the same thing, with the added benefits of remote table access and distributed queries. Microsoft manages the link mechanism via OLE DB technology. Specifically, an OLE DB datasource points to the specific database that can be accessed using OLEDB.
In this article we will be creating a MySQL linked server on SQL Server 2008 and querying a database [TestMove] table shown in the next listing . In reviewing the previous article it may be noticed that the Employees tables was moved to MySQL database TestMove. In running the commands from the mysql> prompt it is assumed that the MySQL Server has been started.

Listing 1: employees table in TestMove

mysql> show tables;
+--------------------+
| Tables_in_testmove |
+--------------------+
| employees          |
+--------------------+
1 row in set (0.09 sec)

mysql>

Creating an ODBC DSN for MySQL

In the previous article on MySQL Servers cited earlier, a DSN was created for moving data. Essentially the same DSN can be used. Herein follows a brief review of the DSN MySQL_Link created along the same lines as in the previous referenced article. The ODBC driver used for creating this ODBC DSN is the one installed on the machine when the MySQL Server was installed as shown.
MySQL Linked Server on SQL Server 2008
The final interactive window where you may test the connectivity is shown in the next figure. You may notice that the database Testmove has been named in the ODBC DSN. The name MySQL_LINK is the ODBC DSN.
MySQL Linked Server on SQL Server 2008
When you close the window after clicking the OK button, a ODBC DSN item will be added to the System DSN tab of the ODBC wizard as shown.
MySQL Linked Server on SQL Server 2008

Steps to create a linked server from Management Studio

Right click the Linked Servers node to display a drop-down menu as shown in the next figure.
MySQL Linked Server on SQL Server 2008
Click on New Linked Server...item. This brings up the New Linked Server window as shown. The window is all empty except for a default Provider.
MySQL Linked Server on SQL Server 2008
The very first thing to do is to provide a name for this linked server. Herein it is LINKED_ MYSQL. We will be using one of the providers [Microsoft OLE DB Provider for ODBC] supported by SQL Server 2008. You may access the list of OLE DB Providers in the Providers sub-folder of the Linked Servers. Provide the other details as shown in the next figure. Make sure they are entered exactly as shown or according to how you have created the database on MySQL Server.
MySQL Linked Server on SQL Server 2008
Click on the Security list item under General in the left. This opens the 'Security' page of the New Linked Server wizard as shown. Change the login from the default "Be made without using a security context" to "Be made using this security context". Enter remote login. In this case it is "root" for the remote login and the password is the one used during the ODBC DSN (also the password for server authentication) creation.
MySQL Linked Server on SQL Server 2008
Make no changes to the Server Options page. Click OK. This creates a linked server Linked_MySQL as shown expanded in the Linked Server's node as shown. You may need to right click and refresh the Linked Servers' node to see the new linked server. As you can see in the figure, the 'User' tables are not displayed.
MySQL Linked Server on SQL Server 2008


Running Queries and reviewing results

Running system stored procedures can provide various levels of information and the database can be queried using the four part syntax and the openquery() method.

Information on the linked server

It is easy to find how the linked server is configured using system stored procedure sp_linkedsrvlogin on the SQL Server 2008. Open a Query window from File | New | Query Current Connection to open the query window and type in the following statement. The next figure shows the statement as well as the returned values. SQL Server 2008 querying has the intellisense report and this must be put to good use.
Exec sp_linkedsrvlogin
This shows all servers both local and remote as shown in the next figure.
MySQL Linked Server on SQL Server 2008
Information about the tables on the remote server can also be accessed by running a stored procedure. Executing the stored procedure sp_tables_ex as shown in the next figure (which displays the statement and the result of executing the stored procedure) can be used to obtain table information.
MySQL Linked Server on SQL Server 2008

Querying the table on the database

Data in the table on the linked server can be queried using the openquery() function. The syntax for this function shown next is very simple.
openquery ('linked server', 'query')
The next figure shows the result of running the openquery() function on the Linked_MySQL linked server.
MySQL Linked Server on SQL Server 2008
Although it should be possible to query the linked server using the four part syntax as in:
Select * from LINKED_MYSQL...employees
The above statement returns an error. This is probably a limitation of a combination of MSDASQL and the ODBC driver which does not provide the schema information correctly(this is just the author's opinion).

Are Remote Procedure Calls (RPC) allowed?

The easiest way to test this is to send out a call by running the following query against the linked server.
Execute('Select FirstName, LastName from employees') at Linked_MYSQL
If the linked server is not configured for RPC, then the result you get by running the above query is as shown in the next figure.
MySQL Linked Server on SQL Server 2008

Turn on RPC

Earlier on we skipped the Server Options page of the linked server. Back in the Management Studio right click linked server LINKED_MYSQL and from the drop-down choose to look at the properties at the bottom of the list. This brings up the LINKED_MYSQL properties window as shown. Click on Server Options. In the Server Options page change the values of RPC and RPCOUT to true, default for both being false.
MySQL Linked Server on SQL Server 2008
Now run the query that produced the error previously. The result is displayed in the next figure.
MySQL Linked Server on SQL Server 2008
You might have noted that only two columns were returned from the employees table. This was deliberate as trying to get all the column would produce an error due partly to the data types of data stored in the table and their compatibility with MSDASQL and the ODBC driver (Again, an author's opinion).

Creating Linked Server using TSQL

While the linked server can be created using the built-in wizard of the Management Studio, it can also be created using TSQL statements as in the following listing (run both statements, the first one creates the linked server and the second the logins).

Listing 2:

 Exec master.dbo.sp_addlinkedserver
@server=N'MySQlbyCode',
@srvprodcut=N'MySQL',
@provider=N'MSDASQL',
@datasrc=N'MySQL_link'

Exec master.dbo.sp_addlinkedserverlogin
@server=N'MySQlbyCode',
@locallogin=NULL,
@rmtuser=N'root',
@rmtpassword=N'<your password>'
@rmtsrvname=N'localhost'

Summary

The article described the steps involved in configuring a MySql Linked server on SQL Server 2008 using the built-in New Linked Server wizard as well as TSQL. Method to query the linked server as well as enabling RPC were described.

Wednesday, 17 September 2014

HOWTO: Setup SQL Server Linked Server to MySQL

Despite being completely proprietary, one of the nice connectivity features offered in SQL Server is the ability to query other servers through a Linked Server. Essentially, a linked server is a method of directly querying another RDBMS; this often happens through the use of an ODBC driver installed on the server. Fortunately, many popular databases provide this ODBC driver, giving SQL Server the ability to connect to a wide range of other systems. I’ve already written about how to connect Oracle and SQL Server. In this post, I’m going to go through the steps necessary to connect SQL Server and MySQL.
The first step is to fetch an appropriate MySQL Connector/ODBC 5.1 download. Drivers are available for a variety of OS‘s, but we’re obviously focused on Windows or Window x64, which should correspond to the version of SQL Server installed. After you’ve downloaded and installed the driver, we have a few things to configure, so let’s get started:

Configure a MySQL DSN

The first step is to configure a MySQL data source by running the ODBC Data Source Administrator. This step is technically entirely optional, but allows a simpler configuration in the SQL Server Linked Server settings. Instead of composing a complicated MySQL connection string, we can use a simple GUI application.
Run odbcad32
Run odbcad32
If you’re using Windows Server 2003, bring up a Run dialog box with Start→Run or WinKey+R. If you’re using Windows Server 2008, use the Start Menu search box directly. In either OS, type in “odbcad32″ and hit Enter.
System DSN
System DSN
Select the System DSN tab to configure a data source for the entire system. If you only want to create the DSN for a specific user (such as your service account), use the User DSN tab. In either scenario, select the “Add…” button.
Create New Data Source
Create New Data Source
Scroll down in the Create New Data Source window and select “MySQL ODBC 3.51 Driver” and click “Finish”.
MySQL Connector Login Settings
MySQL Connector Login Settings
Once added, clicking the “Configure…” button will bring up the Connector/ODBC 3.51 Configure Data Source application. This is where you can specify all the connection settings for connecting SQL Server to MySQL. Select a Data Source Name – I typically name it after the application or database I’m connecting to. The Server, User, Password, and Database should all be obvious.
Test ODBC Connection
Test ODBC Connection
After you’ve entered all the required parameters, click the “Test” button to ensure a connection can be made to the MySQL server.
These settings are the bare minimum required to connect MySQL and SQL Server via a linked server, but I like to specify additional options to optimize the connection between the servers. Without these, I have run into “Out of Memory” errors that require restarting the service.
MySQL Connector Advanced Flags 1 Settings
MySQL Connector Advanced Flags 1 Settings
Select the Advanced tab and you’ll be placed on the “Flags 1″ sub-tab. Check the boxes labeled “Allow Big Results” and “Use Compressed Protocol”.
MySQL Connector Advanced Flags 2 Settings
MySQL Connector Advanced Flags 2 Settings
Next, switch to the “Flags 2″ tab and select “Don’t Cache Result (forward only cursors)”. This can actually be a performance penalty if you perform the same query multiple times to the same linked server. However, in my experience, the reason to connect SQL Server to MySQL, is to pull data into a single server, in which case, this option is perfectly suited.
MySQL Connector Advanced Flags 3 Settings
MySQL Connector Advanced Flags 3 Settings
On the “Flags 3″ tab, select “Force Use Of Forward Only Cursors”. When you’re done setting all these options, select the “Ok” button.

Configure Linked Server Provider

Adjusting the Linked Server Provider is simple, but it comes with a caveat: When adjusting a provider, you are adjusting it for all connections using that provider. I am not aware of any way to change these settings on a per-connection basis.
Provider Properties
Provider Properties
Drill down to Server Object → Linked Servers → Providers, right-click MSDASQL, and select “Properties”.
Set Provider Options
Set Provider Options
The Provider Options for Microsoft OLE DB Provider for ODBC Drivers dialog box will open allowing you to configure several options. Ensure the following four options are checked:
  • Nested queries
  • Level zero only
  • Allow inprocess
  • Supports ‘Like’ Operator
All other options should be unchecked. When done, click “OK”.

Create Linked Server to MySQL

Finally, the last step in our process is to create the actual MySQL Linked Server.
Create a New Linked Server
Create a New Linked Server
You should already have Linked Servers expanded in the Object Explorer tree. If not, find it in Server Objects → Linked Server. Once there, right-click Linked Servers and select “New Linked Server…”
New linked Server Settings
New linked Server Settings
The New Linked Server dialog box will open. Because we specified all our connection settings in the ODBC Data Source Administrator, this last step is very simple. Name the linked server. As with the Data Source Name, I like to name it after the product or database I’m connecting to. In my example, I used MYSQLAPP. Ensure that the “Other data source” option is selected and choose “Microsoft OLE DB Provider for ODBC Drivers” from the Provider dropdown. Lastly, specify the Product name and Data source. The Product name doesn’t matter so much as the Data source must match what you provided in the MySQL Connector/ODBC configuration. Press “OK” when complete.

Testing the SQL Server to MySQL connection

If everything has been set correctly, you should be able to execute a query directly again the MySQL database from SQL Server Management Studio. For example:
SELECT TOP 10 TABLE_NAME FROM MYSQLAPP...tables WHERE TABLE_TYPE != 'MEMORY'
If you’ve done everything correctly, you should get back a result set. There are several error message you might receive:
OLE DB provider "MSDASQL" for linked server "MYSQLAPP" returned message "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "MYSQLAPP".
The message indicates that the Data source name you’ve specified for the linked server does not match that of the Data Source Name specified in the MySQL Connector.
Msg 7313, Level 16, State 1, Line 1
An invalid schema or catalog was specified for the provider "MSDASQL" for linked server "MySQLApp".
This uninsightful error is a result of not correctly setting the options for the Linked Server Provider.
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "MSDASQL" for linked server "MySQLApp" reported an error. The provider did not give any information about the error.
Msg 7312, Level 16, State 1, Line 1
Invalid use of schema or catalog for OLE DB provider "MSDASQL" for linked server "MySQLApp". A four-part name was supplied, but the provider does not expose the necessary interfaces to use a catalog or schema.
This “four-part name” error is due to a limitation in the MySQL ODBC driver. You cannot switch catalogs/schemas using dotted notation. Instead, you will have to register another DSN and Linked Server for the different catalogs you want to access. Be sure and follow the three-dot notation noted in the example query.
If, however, you want to access other schemas, you can do so utilizing OPENQUERY. This is also a great way to test your connection if you’re receiving problems. The syntax looks like this:
SELECT * FROM OPENQUERY(MYSQLAPP, 'SELECT * FROM INFORMATION_SCHEMA.TABLES LIMIT 10')
Notice that the actual query syntax in the string must be in the MySQL format (SQL Server does not support the LIMIT keyword). Additionally, you can specify a different schema using SCHEMA.TABLENAME in the query.

Conclusion

Creating a linked server between SQL Server and MySQL is a simple process. The first time requires you to install the software and configure the Linked Server Provider, but all subsequent connections require only a DSN and Linked Server.

92 thoughts on “HOWTO: Setup SQL Server Linked Server to MySQL

I have solved my issue by, Create link server by executing following query syntax.
  1. EXEC master.dbo.sp_addlinkedserver @server=’MYSQL’, @srvproduct=’ MYSQL ‘, @provider=’MSDASQL’,
    @datasrc=’MYSQL32′, @provstr=’DRIVER={MySQL ODBC 5.1 Driver};SERVER=192.168.241.32;Port=3306;USER=root;PASSWORD=12345;OPTION=3;DATABASE=cms_test;’

    Thanks…
     
     
     
     I have DNS for mysql to connect data in SQL Server. Connection stsus showing successfully on DNS Setting winow.
    Bur getting following erron in SQL, during making link server.

    “Cannot initialize the data source object of OLE DB provider “MSDASQL” for linked server “MYSQLAPP”.
    OLE DB provider “MSDASQL” for linked server “MYSQLAPP” returned message “[MySQL][ODBC 5.1 Driver]Access denied for user ‘root’@’localhost’ (using password: NO)”. (Microsoft SQL Server, Error: 7303)

    please give some solution.

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...