centos安装freetds使php支持sqlserver操作

因为项目需要,需要在linux上面操作sqlserver数据库,但是php默认安装是不支持的,所以需要手动配置下,这里使用的shell脚本自动安装配置 

freetds是一个程序库,可以实现在linux系统下访问微软的sql数据库

注意事项:

1、当时因为乱码问题调试了挺久,解决办法:freetds.conf 数据源一定要指定编码client charset = UTF-8

2、本质是借助pdo的odbc进行操作,所以pdo和odbc扩展要先装好,如果没有pdo,也可使用php自带的mssql扩展进行操作mssql_connect,mssql_query

3、sqlserver开了远程后可使用工具Navicat for SQL Server,挺好用的


开始安装过程

1、执行安装脚本

#sudo sh ./odbc.sh

odbc.sh脚本内容 

#!/bin/bash

export SQL_SERVER_ADDRESS="192.168.10.111"
export DATABASE_NAME="THIS05"

#DSN = Data Source Name. This is a reference name, and can be set to any label you wish.
export MY_DSN="server-dsn"

yum install unixODBC unixODBC-devel -y
cd /tmp

wget http://ibiblio.org/pub/Linux/ALPHA/freetds/stable/freetds-stable.tgz
tar zxvf freetds-stable.tgz

cd freetds-*
./configure --prefix=/usr --sysconfdir=/etc --with-tdsver=0.91 --enable-msdblib
make
make install

cat <<EOF >> /etc/odbc.ini
[$MY_DSN]
Driver = FreeTDS
Description = Microsoft SQL
Server = $SQL_SERVER_ADDRESS
Port = 1433
Database = $DATABASE_NAME
TDS_Version = 8.0
EOF

cat <<EOF >> /etc/odbcinst.ini
[FreeTDS]
Description     = FreeTDS unixODBC Driver
Driver          = /usr/lib/libtdsodbc.so
Setup           = /usr/lib/libtdsodbc.so
EOF

cat <<EOF >> /etc/freetds.conf
[$MY_DSN]
        host = $SQL_SERVER_ADDRESS
        port = 1433
        tds version = 8.0
		client charset = UTF-8
EOF

2、命令行测试

#tsql -S server-dsn -U sa -P xxxxxx
locale is "zh_CN.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
1> use THIS05
2> go
1> select @@version
2> go


Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
        Jul  9 2008 14:43:34
        Copyright (c) 1988-2008 Microsoft Corporation
        Enterprise Edition on Windows NT 6.0 <X86> (Build 6002: Service Pack 2) (VM)


(1 row affected)
1> bye


3、php代码测试

<?php 
$conn = new PDO("odbc:Driver=FreeTDS;Server={IP};Port={Port};Database={DBName};Tds_version=7.2;Client_charset=UTF-8;Uid={Username};Pwd={Password};");
$sql = 'SELECT * FROM {Table}';
foreach ($conn->query($sql) as $row) {
    print_r($row);
}
?>





你可能感兴趣的:(MSSQL,sqlserver,FreeTDS)