在Ubuntu下使用Fortran连接数据库,通常需要借助外部库来实现。以下是一些常见的数据库和相应的连接方法:
sudo apt-get update
sudo apt-get install libmysqlclient-dev
你可以使用libmysqlclient库来连接MySQL数据库。以下是一个简单的示例代码:
program mysql_example
use, intrinsic :: iso_c_binding
implicit none
interface
subroutine mysql_init(conn) bind(c, name="mysql_init")
import :: c_ptr
type(c_ptr), intent(out) :: conn
end subroutine mysql_init
subroutine mysql_real_connect(conn, host, user, passwd, db, port, unix_socket, client_flag) bind(c, name="mysql_real_connect")
import :: c_ptr, c_char, c_int
type(c_ptr), value :: conn
type(c_char), intent(in) :: host(*), user(*), passwd(*), db(*)
integer(c_int), value :: port, client_flag
type(c_ptr), intent(in), optional :: unix_socket
end subroutine mysql_real_connect
subroutine mysql_close(conn) bind(c, name="mysql_close")
import :: c_ptr
type(c_ptr), value :: conn
end subroutine mysql_close
! 其他必要的MySQL函数...
end interface
type(c_ptr) :: conn
character(len=255) :: host, user, passwd, db
integer(c_int) :: port, client_flag
host = 'localhost'
user = 'your_username'
passwd = 'your_password'
db = 'your_database'
port = 3306
client_flag = 0
conn = mysql_init(C_NULL_PTR)
if (conn == C_NULL_PTR) then
print *, 'MySQL initialization failed'
stop
end if
conn = mysql_real_connect(conn, host, user, passwd, db, port, C_NULL_PTR, client_flag)
if (conn == C_NULL_PTR) then
print *, 'MySQL connection failed'
call mysql_close(conn)
stop
end if
print *, 'Connected to MySQL database'
! 执行SQL查询...
call mysql_close(conn)
print *, 'Disconnected from MySQL database'
end program mysql_example
sudo apt-get update
sudo apt-get install libpq-dev
你可以使用libpq库来连接PostgreSQL数据库。以下是一个简单的示例代码:
program pgsql_example
use, intrinsic :: iso_c_binding
implicit none
interface
subroutine PQconnectdb(conninfo) bind(c, name="PQconnectdb")
import :: c_char_p, c_ptr
type(c_char_p), value :: conninfo
type(c_ptr), intent(out) :: conn
end subroutine PQconnectdb
subroutine PQfinish(conn) bind(c, name="PQfinish")
import :: c_ptr
type(c_ptr), value :: conn
end subroutine PQfinish
! 其他必要的PostgreSQL函数...
end interface
type(c_ptr) :: conn
character(len=255) :: conninfo
conninfo = 'host=localhost dbname=your_database user=your_username password=your_password'
conn = PQconnectdb(conninfo)
if (conn == C_NULL_PTR) then
print *, 'PostgreSQL connection failed'
stop
end if
print *, 'Connected to PostgreSQL database'
! 执行SQL查询...
call PQfinish(conn)
print *, 'Disconnected from PostgreSQL database'
end program pgsql_example
编译Fortran代码时,需要链接相应的库。例如,对于MySQL示例:
gfortran -o mysql_example mysql_example.f90 -lmysqlclient
对于PostgreSQL示例:
gfortran -o pgsql_example pgsql_example.f90 -lpq
-L选项。通过以上步骤,你应该能够在Ubuntu下使用Fortran连接数据库。