SQL Server PDO could not find driver

2020-05-08 08:15发布

问题:

I'm using Microsoft Azure SQL for my database and I'm trying to connect it to my project on my localhost using XAMPP. When I try to connect to the database using the connect string they provided:

    try {
    $conn = new PDO("sqlsrv:server = tcp:app.database.windows.net,1433; Database = mydatabase", "{myusername}", "{your_password_here}");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
    print("Error connecting to SQL Server.");
    die(print_r($e));
}

I keep getting this error:

Error connecting to SQL Server.PDOException Object ( [message:protected] => could not find driver

The error is longer but I think it's related to the driver mentioned at the end. I'm using a mac so any driver I need to install would need to be compatible with it. Thank you for the help in advance.

回答1:

Azure SQL Database is built on the Microsoft SQL Server engine. So you might consider using pdo-dblib to connect to SQL Server using the PDO on a Mac. You can check out a Stack Overflow question about it here or refer to this setup documentation.

After the driver having been installed, Azure SQL won’t actually accept connection from your local yet. And you might get the following error:

Client with IP address '167.xxx.xxx.xxx' is not allowed to access the server.

That’s because there is a firewall in the way by default. To enable access, go to the Azure portal, click on All Resources, select your SQL service, click on Firewall in the SETTING menu.

Your client address is conveniently included in the list, so you can just click on Add client IP followed by Save.

Well, when you run your code now, it should connect.