MySQL支持多种编程语言,以下是一些常见的编程语言和它们与MySQL的集成方式:
Python:可以使用
mysql-connector-python
库来连接和操作MySQL数据库。例如:import mysql.connector cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='database_name') cursor = cnx.cursor() cursor.execute("SELECT * FROM table_name") results = cursor.fetchall() cnx.close()
Java:可以使用
JDBC
(Java Database Connectivity)驱动程序来连接和操作MySQL数据库。例如:import java.sql.*; public class Main { public static void main(String[] args) { try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database_name", "username", "password"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM table_name"); while (rs.next()) { System.out.println(rs.getString("column_name")); } con.close(); } catch (Exception e) { System.err.println(e); } } }
PHP:可以使用
mysqli
扩展或PDO
(PHP Data Objects)来连接和操作MySQL数据库。例如:$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // Create connection using mysqli $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create connection using PDO $dsn = "mysql:host=$servername;dbname=$dbname"; $pdo = new PDO($dsn, $username, $password);
C#:可以使用
MySql.Data
库来连接和操作MySQL数据库。例如:using MySql.Data.MySqlClient; var connectionString = "Server=localhost;Database=database_name;Uid=username;Pwd=password;"; using var connection = new MySqlConnection(connectionString); connection.Open(); var command = new MySqlCommand("SELECT * FROM table_name", connection); using var reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["column_name"]); }
Ruby:可以使用
mysql2
gem来连接和操作MySQL数据库。例如:require 'mysql2' client = Mysql2::Client.new(:host => "localhost", :username => "username", :password => "password", :database => "database_name") results = client.query("SELECT * FROM table_name") results.each do |row| puts row['column_name'] end
除了上述语言外,还有许多其他编程语言也提供了与MySQL交互的方法,如Node.js、Go、Rust等。这些语言通常使用相应的数据库驱动程序或库来实现与MySQL的连接和操作。