Untuk mengakses database MySQL dengan Node. js, Anda memerlukan driver MySQL. Tutorial ini akan menggunakan modul "mysql", yang diunduh dari NPM
Untuk mengunduh dan menginstal modul "mysql", buka Terminal Perintah dan jalankan perintah berikut
C. \Users\Nama Anda>npm instal mysql
Sekarang Anda telah mengunduh dan menginstal driver database mysql
Node. js dapat menggunakan modul ini untuk memanipulasi database MySQL
var mysql = membutuhkan('mysql');
Buat Koneksi
Mulailah dengan membuat koneksi ke database
Gunakan username dan password dari database MySQL Anda
demo_db_koneksi. js
var mysql = membutuhkan('mysql');
var con = mysql. buatKoneksi({
tuan rumah. "localhost",
pengguna. "nama pengguna Anda",
kata sandi. "kata sandi Anda"
});
menipu. terhubung(fungsi(err) {
jika (err) lempar err;
menghibur. log("Terhubung. ");
});
Simpan kode di atas dalam file bernama "demo_db_connection. js" dan jalankan file
Jalankan "demo_db_connection. js"
C. \Users\Nama Anda>node demo_db_connection. js
Yang akan memberi Anda hasil ini
Sekarang Anda dapat mulai membuat kueri database menggunakan pernyataan SQL
Meminta Database
Gunakan pernyataan SQL untuk membaca dari (atau menulis ke) database MySQL. Ini juga disebut "untuk menanyakan" basis data
Kode C API didistribusikan dengan MySQL. Itu termasuk dalam perpustakaan mysqlclient dan memungkinkan program C untuk mengakses database
Banyak klien dalam distribusi sumber MySQL ditulis dalam C. Jika Anda mencari contoh yang mendemonstrasikan cara menggunakan C API, lihat klien ini. Anda dapat menemukannya di direktori klien di distribusi sumber MySQL
Sebagian besar API klien lain (semuanya kecuali Java) menggunakan pustaka mysqlclient untuk berkomunikasi dengan server MySQL. Ini berarti bahwa, misalnya, Anda dapat memanfaatkan banyak variabel lingkungan yang sama yang digunakan oleh program klien lain karena direferensikan dari pustaka. Lihat Bagian 4. 8, untuk daftar variabel-variabel ini
Klien memiliki ukuran buffer komunikasi maksimum. Ukuran buffer yang dialokasikan pada awalnya (16K byte) secara otomatis ditingkatkan hingga ukuran maksimum (maksimum 16M). Karena ukuran buffer ditingkatkan hanya sebagai jaminan permintaan, hanya meningkatkan batas maksimum default tidak dengan sendirinya menyebabkan lebih banyak sumber daya yang digunakan. Pemeriksaan ukuran ini sebagian besar merupakan pemeriksaan untuk kueri dan paket komunikasi yang salah
Penyangga komunikasi harus cukup besar untuk memuat satu pernyataan SQL (untuk lalu lintas klien-ke-server) dan satu baris data yang dikembalikan (untuk lalu lintas server-ke-klien). Penyangga komunikasi setiap utas diperbesar secara dinamis untuk menangani kueri atau baris apa pun hingga batas maksimum. Misalnya, jika Anda memiliki nilai BLOB yang berisi hingga 16M data, Anda harus memiliki batas buffer komunikasi minimal 16M (di server dan klien). Maksimum default klien adalah 16M, tetapi maksimum default di server adalah 1M. Anda dapat meningkatkannya dengan mengubah nilai parameter max_allowed_packet saat server dimulai. Melihat
Server MySQL mengecilkan setiap buffer komunikasi menjadi byte net_buffer_length setelah setiap kueri. Untuk klien, ukuran buffer yang terkait dengan koneksi tidak berkurang hingga koneksi ditutup, saat memori klien diklaim kembali
Untuk pemrograman dengan utas, lihat. Untuk membuat aplikasi mandiri yang menyertakan "server" dan "klien" dalam program yang sama (dan tidak berkomunikasi dengan server MySQL eksternal), lihat
MYSQL
Struktur ini merupakan pegangan untuk satu koneksi database. Ini digunakan untuk hampir semua fungsi MySQL
MYSQL_RESStruktur ini mewakili hasil kueri yang mengembalikan baris (SELECT, SHOW, DESCRIBE, EXPLAIN). Informasi yang dikembalikan dari kueri disebut set hasil di sisa bagian ini
MYSQL_ROWIni adalah representasi tipe-aman dari satu baris data. Saat ini diimplementasikan sebagai larik string byte yang dihitung. (Anda tidak dapat memperlakukan ini sebagai string yang diakhiri null jika nilai kolom mungkin berisi data biner karena nilai tersebut mungkin berisi byte null secara internal. ) Baris diperoleh dengan memanggil mysql_fetch_row()
MYSQL_FIELDStruktur ini berisi informasi tentang bidang, seperti nama, jenis, dan ukuran bidang. Anggotanya dijelaskan lebih rinci nanti. Anda dapat memperoleh struktur MYSQL_FIELD untuk setiap bidang dengan memanggil mysql_fetch_field() berulang kali. Nilai bidang bukan bagian dari struktur ini;
MYSQL_FIELD_OFFSETIni adalah representasi tipe-aman dari offset ke dalam daftar bidang MySQL (digunakan oleh mysql_field_seek( )). Offset adalah nomor bidang dalam satu baris, dimulai dari nol
my_ulonglongJenis yang digunakan untuk jumlah baris dan untuk mysql_affected_rows( ), mysql_num_rows( ), dan mysql_insert_id( ). Tipe ini menyediakan rentang 0 hingga 1. 84e19
Pada beberapa sistem, mencoba untuk mencetak nilai tipe my_ulonglong tidak akan berhasil. Untuk mencetak nilai seperti itu, ubah menjadi unsigned long dan gunakan format cetak %lu. Contoh
printf (Number of rows: %lu\n", (unsigned long) mysql_num_rows(result));Struktur MYSQL_FIELD berisi anggota berikut
nama karakter
Nama bidang, sebagai string yang diakhiri null
tabel char *Nama tabel yang berisi kolom ini, jika bukan kolom kalkulasi. Untuk kolom kalkulasi, nilai tabel adalah string kosong
char * defNilai default bidang ini, sebagai string yang diakhiri null. Ini disetel hanya jika Anda menggunakan mysql_list_fields()
jenis enum enum_field_typesJenis lapangan. Nilai tipe mungkin salah satu dari berikut ini
Ketik nilai
Ketik deskripsi
FIELD_TYPE_TINY
bidang TINYINT
FIELD_TYPE_SHORT
bidang KECIL
FIELD_TYPE_LONG
bidang INTEGER
FIELD_TYPE_INT24
bidang SEDANG
FIELD_TYPE_LONGLONG
bidang BESAR
FIELD_TYPE_DECIMAL
bidang DECIMAL atau NUMERIK
FIELD_TYPE_FLOAT
bidang TERAPUNG
LAPANGAN_TYPE_DOUBLE
bidang GANDA atau NYATA
FIELD_TYPE_TIMESTAMP
kolom TIMESTAMP
FIELD_TYPE_DATE
bidang TANGGAL
FIELD_TYPE_TIME
bidang WAKTU
FIELD_TYPE_DATETIME
kolom DATETIME
LAPANGAN_TYPE_TAHUN
bidang TAHUN
FIELD_TYPE_STRING
Bidang string (CHAR atau VARCHAR).
FIELD_TYPE_BLOB
Bidang BLOB atau TEXT (gunakan max_length untuk menentukan panjang maksimum)
FIELD_TYPE_SET
bidang SET
FIELD_TYPE_ENUM
bidang ENUM
FIELD_TYPE_NULL
bidang tipe NULL
FIELD_TYPE_CHAR
Tidak digunakan lagi;
Anda dapat menggunakan makro IS_NUM( ) untuk menguji apakah bidang memiliki tipe numerik. Berikan nilai tipe ke IS_NUM( ) dan akan dievaluasi ke TRUE jika bidangnya numerik
if (IS_NUM(field->type)) printf("Field is numeric\n");_panjang int tidak bertanda tanganLebar bidang, seperti yang ditentukan dalam definisi tabel
unsigned int max_lengthLebar maksimum bidang untuk kumpulan hasil (panjang dari nilai bidang terpanjang untuk baris sebenarnya dalam kumpulan hasil). Jika Anda menggunakan mysql_store_result( ) atau mysql_list_fields( ), ini berisi panjang maksimum untuk bidang tersebut. Jika Anda menggunakan mysql_use_result() , nilai variabel ini adalah nol
bendera int yang tidak ditandatanganiBit-flag yang berbeda untuk bidang tersebut. Nilai bendera mungkin memiliki nol atau lebih dari set bit berikut
Tandai nilai
Deskripsi bendera
NOT_NULL_FLAG
Kolom tidak boleh NULL
PRI_KEY_FLAG
Bidang adalah bagian dari kunci utama
UNIK_KEY_FLAG
Bidang adalah bagian dari kunci unik
GANDA_KEY_BENDERA
Bidang adalah bagian dari kunci non-unik
UNSIGNED_FLAG
Bidang memiliki atribut UNSIGNED
ZEROFILL_FLAG
Bidang memiliki atribut ZEROFILL
BINARY_FLAG
Bidang memiliki atribut BINARY
AUTO_INCREMENT_FLAG
Bidang memiliki atribut AUTO_INCREMENT
ENUM_FLAG
Bidang adalah ENUM (tidak digunakan lagi)
SET_FLAG
Bidang adalah SET (usang)
BLOB_FLAG
Bidang adalah BLOB atau TEXT (usang)
TIMESTAMP_FLAG
Bidang adalah TIMESTAMP (usang)
Penggunaan flag BLOB_FLAG, ENUM_FLAG, SET_FLAG, dan TIMESTAMP_FLAG tidak digunakan lagi karena menunjukkan jenis bidang daripada atribut jenisnya. Lebih baik menguji field->type terhadap FIELD_TYPE_BLOB, FIELD_TYPE_ENUM, FIELD_TYPE_SET, atau FIELD_TYPE_TIMESTAMP sebagai gantinya
Contoh berikut mengilustrasikan penggunaan umum dari nilai flags
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");Anda dapat menggunakan makro kemudahan berikut untuk menentukan status boolean dari nilai bendera
Tandai status
Keterangan
IS_NOT_NULL(bendera)
Benar jika kolom ini didefinisikan sebagai NOT NULL
IS_PRI_KEY(bendera)
Benar jika bidang ini adalah kunci utama
IS_BLOB(bendera)
Benar jika kolom ini berupa BLOB atau TEXT (usang; kolom uji->ketik sebagai gantinya)
int desimal yang tidak ditandatanganiJumlah desimal untuk bidang numerik
Fungsi-fungsi yang tersedia di C API dicantumkan berikutnya dan dijelaskan secara lebih rinci di bagian selanjutnya. Melihat
Fungsi
Keterangan
mysql_affected_rows()
Mengembalikan jumlah baris yang diubah/dihapus/disisipkan oleh kueri UPDATE, DELETE, atau INSERT terakhir
mysql_change_user()
Mengubah pengguna dan basis data pada koneksi terbuka
mysql_character_set_name( )
Mengembalikan nama set karakter default untuk koneksi
mysql_close()
Menutup koneksi server
mysql_connect()
Terhubung ke server MySQL. Fungsi ini sudah tidak digunakan lagi;
mysql_create_db( )
Membuat basis data. Fungsi ini sudah tidak digunakan lagi;
mysql_data_seek( )
Mencari baris arbitrer dalam kumpulan hasil kueri
mysql_debug()
Apakah DBUG_PUSH dengan string yang diberikan
mysql_drop_db( )
Menjatuhkan database. Fungsi ini sudah tidak digunakan lagi;
mysql_dump_debug_info( )
Membuat server menulis informasi debug ke log
mysql_eof()
Menentukan apakah baris terakhir dari kumpulan hasil telah dibaca. Fungsi ini sudah tidak digunakan lagi;
mysql_errno( )
Mengembalikan nomor kesalahan untuk fungsi MySQL yang terakhir dipanggil
mysql_error()
Mengembalikan pesan kesalahan untuk fungsi MySQL yang terakhir dipanggil
mysql_escape_string( )
Melarikan diri dari karakter khusus dalam string untuk digunakan dalam pernyataan SQL
mysql_fetch_field( )
Mengembalikan jenis bidang tabel berikutnya
mysql_fetch_field_direct()
Mengembalikan jenis bidang tabel, diberi nomor bidang
mysql_fetch_fields()
Mengembalikan array dari semua struktur bidang
mysql_fetch_lengths()
Mengembalikan panjang semua kolom di baris saat ini
mysql_fetch_row( )
Mengambil baris berikutnya dari kumpulan hasil
mysql_field_seek( )
Menempatkan kursor kolom pada kolom tertentu
mysql_field_count()
Mengembalikan jumlah kolom hasil untuk kueri terbaru
mysql_field_tell( )
Mengembalikan posisi kursor bidang yang digunakan untuk mysql_fetch_field( ) terakhir
mysql_free_result( )
Membebaskan memori yang digunakan oleh kumpulan hasil
mysql_get_client_info( )
Mengembalikan informasi versi klien
mysql_get_host_info( )
Mengembalikan string yang menjelaskan koneksi
mysql_get_proto_info( )
Mengembalikan versi protokol yang digunakan oleh koneksi
mysql_get_server_info( )
Mengembalikan nomor versi server
mysql_info( )
Mengembalikan informasi tentang kueri yang terakhir dieksekusi
mysql_init()
Mendapat atau menginisialisasi struktur MySQL
mysql_insert_id( )
Mengembalikan ID yang dihasilkan untuk kolom AUTO_INCREMENT oleh kueri sebelumnya
mysql_kill()
Membunuh utas yang diberikan
mysql_list_dbs( )
Mengembalikan nama database yang cocok dengan ekspresi reguler sederhana
mysql_list_fields()
Mengembalikan nama bidang yang cocok dengan ekspresi reguler sederhana
mysql_list_processes()
Mengembalikan daftar utas server saat ini
mysql_list_tables( )
Mengembalikan nama tabel yang cocok dengan ekspresi reguler sederhana
mysql_num_fields()
Mengembalikan jumlah kolom dalam kumpulan hasil
mysql_num_rows( )
Mengembalikan jumlah baris dalam kumpulan hasil
mysql_options()
Setel opsi koneksi untuk mysql_connect()
mysql_ping()
Memeriksa apakah koneksi ke server berfungsi, menghubungkan kembali seperlunya
mysql_query()
Mengeksekusi kueri SQL yang ditetapkan sebagai string yang diakhiri null
mysql_real_connect()
Terhubung ke server MySQL
mysql_real_escape_string()
Melarikan diri dari karakter khusus dalam string untuk digunakan dalam pernyataan SQL, dengan mempertimbangkan rangkaian karakter koneksi saat ini
mysql_real_query( )
Mengeksekusi kueri SQL yang ditentukan sebagai string terhitung
mysql_reload()
Memberitahu server untuk memuat ulang tabel hibah
mysql_row_seek( )
Mencari baris dalam kumpulan hasil, menggunakan nilai yang dikembalikan dari mysql_row_tell()
mysql_row_tell( )
Mengembalikan posisi kursor baris
mysql_select_db( )
Memilih basis data
mysql_shutdown()
Mematikan server basis data
mysql_stat()
Mengembalikan status server sebagai string
mysql_store_result( )
Mengambil hasil lengkap yang ditetapkan ke klien
mysql_thread_id( )
Mengembalikan ID utas saat ini
mysql_thread_safe( )
Mengembalikan 1 jika klien dikompilasi sebagai thread-safe
mysql_use_result()
Memulai pengambilan kumpulan hasil baris demi baris
Untuk terhubung ke server, panggil mysql_init( ) untuk menginisialisasi pengendali koneksi, lalu panggil mysql_real_connect( ) dengan pengendali tersebut (bersama dengan informasi lain seperti nama host, nama pengguna, dan kata sandi). Setelah koneksi, mysql_real_connect() menyetel bendera sambungkan kembali (bagian dari struktur MYSQL) ke nilai 1. Bendera ini menunjukkan, jika kueri tidak dapat dilakukan karena koneksi terputus, untuk mencoba menyambung kembali ke server sebelum menyerah. Ketika Anda selesai dengan koneksi, panggil mysql_close() untuk menghentikannya
Saat koneksi aktif, klien dapat mengirim kueri SQL ke server menggunakan mysql_query( ) atau mysql_real_query(). Perbedaan antara keduanya adalah bahwa mysql_query( ) mengharapkan kueri ditentukan sebagai string yang diakhiri null, sedangkan mysql_real_query( ) mengharapkan string yang dihitung. Jika string berisi data biner (yang mungkin menyertakan byte nol), Anda harus menggunakan mysql_real_query()
Untuk setiap kueri non-PILIH (misalnya, INSERT, UPDATE, DELETE), Anda dapat mengetahui berapa banyak baris yang diubah (terpengaruh) dengan memanggil mysql_affected_rows()
Untuk kueri SELECT, Anda mengambil baris yang dipilih sebagai kumpulan hasil. (Perhatikan bahwa beberapa pernyataan seperti SELECT karena mengembalikan baris. Ini termasuk MENUNJUKKAN, MENJELASKAN, dan MENJELASKAN. Mereka harus diperlakukan dengan cara yang sama seperti pernyataan SELECT. )
Ada dua cara bagi klien untuk memproses kumpulan hasil. Salah satu caranya adalah mengambil seluruh set hasil sekaligus dengan memanggil mysql_store_result(). Fungsi ini memperoleh dari server semua baris yang dikembalikan oleh kueri dan menyimpannya di klien. Cara kedua adalah agar klien memulai pengambilan set hasil baris demi baris dengan memanggil mysql_use_result(). Fungsi ini menginisialisasi pengambilan, tetapi sebenarnya tidak mendapatkan baris apa pun dari server
Dalam kedua kasus tersebut, Anda mengakses baris dengan memanggil mysql_fetch_row(). Dengan mysql_store_result() , mysql_fetch_row() mengakses baris yang telah diambil dari server. Dengan mysql_use_result() , mysql_fetch_row() sebenarnya mengambil baris dari server. Informasi tentang ukuran data di setiap baris tersedia dengan memanggil mysql_fetch_lengths()
Setelah Anda selesai dengan kumpulan hasil, panggil mysql_free_result() untuk membebaskan memori yang digunakan untuk itu
Kedua mekanisme pengambilan tersebut saling melengkapi. Program klien harus memilih pendekatan yang paling tepat untuk kebutuhan mereka. Dalam praktiknya, klien cenderung menggunakan mysql_store_result() lebih umum
Keuntungan dari mysql_store_result( ) adalah karena semua baris telah diambil ke klien, Anda tidak hanya dapat mengakses baris secara berurutan, tetapi Anda juga dapat bergerak bolak-balik dalam kumpulan hasil menggunakan mysql_data_seek( ) atau mysql_row_seek( ) untuk mengubah . Anda juga dapat mengetahui berapa banyak baris yang ada dengan memanggil mysql_num_rows(). Di sisi lain, persyaratan memori untuk mysql_store_result() mungkin sangat tinggi untuk rangkaian hasil yang besar, sehingga Anda lebih mungkin mengalami kondisi kehabisan memori
Keuntungan dari mysql_use_result( ) adalah bahwa klien membutuhkan lebih sedikit memori untuk kumpulan hasil karena hanya mempertahankan satu baris pada satu waktu (dan karena ada sedikit overhead alokasi, mysql_use_result( ) bisa lebih cepat). Kerugiannya adalah Anda harus memproses setiap baris dengan cepat untuk menghindari mengikat server, Anda tidak memiliki akses acak ke baris dalam rangkaian hasil (Anda hanya dapat mengakses baris secara berurutan), dan Anda tidak tahu berapa banyak baris di . Selain itu, Anda harus mengambil semua baris bahkan jika Anda menentukan di tengah pengambilan bahwa Anda telah menemukan informasi yang Anda cari
API memungkinkan klien untuk merespons kueri dengan tepat (mengambil baris seperlunya saja) tanpa mengetahui apakah kueri tersebut adalah SELECT. Anda dapat melakukannya dengan memanggil mysql_store_result( ) setelah setiap mysql_query( ) (atau mysql_real_query( )). Jika panggilan set hasil berhasil, kueri adalah SELECT dan Anda dapat membaca barisnya. Jika panggilan set hasil gagal, panggil mysql_field_count() untuk menentukan apakah hasil benar-benar diharapkan. Jika mysql_field_count() mengembalikan nol, kueri tidak mengembalikan data (menunjukkan bahwa itu adalah INSERT, UPDATE, DELETE, dll. ), dan tidak diharapkan untuk mengembalikan baris. Jika mysql_field_count() bukan nol, kueri seharusnya mengembalikan baris, tetapi tidak. Ini menunjukkan bahwa kueri adalah SELECT yang gagal. Lihat deskripsi untuk mysql_field_count() untuk contoh bagaimana hal ini dapat dilakukan
Baik mysql_store_result() dan mysql_use_result() memungkinkan Anda memperoleh informasi tentang bidang yang menyusun kumpulan hasil (jumlah bidang, nama dan jenisnya, dll. ). Anda dapat mengakses informasi bidang secara berurutan di dalam baris dengan memanggil mysql_fetch_field( ) berulang kali, atau dengan nomor bidang di dalam baris dengan memanggil mysql_fetch_field_direct(). Posisi kursor bidang saat ini dapat diubah dengan memanggil mysql_field_seek(). Menyetel kursor bidang memengaruhi panggilan selanjutnya ke mysql_fetch_field(). Anda juga bisa mendapatkan informasi untuk bidang sekaligus dengan memanggil mysql_fetch_fields()
Untuk mendeteksi dan melaporkan kesalahan, MySQL menyediakan akses ke informasi kesalahan melalui fungsi mysql_errno( ) dan mysql_error( ). Ini mengembalikan kode kesalahan atau pesan kesalahan untuk fungsi yang terakhir dipanggil yang bisa berhasil atau gagal, memungkinkan Anda untuk menentukan kapan kesalahan terjadi dan apa itu
Deskripsi Fungsi C API
Pada uraian berikut, parameter atau nilai kembalian NULL berarti NULL dalam pengertian bahasa pemrograman C, bukan nilai MySQL NULL
Fungsi yang mengembalikan nilai biasanya mengembalikan pointer atau bilangan bulat. Kecuali ditentukan lain, fungsi yang mengembalikan pointer mengembalikan nilai non-NULL untuk menunjukkan keberhasilan atau nilai NULL untuk menunjukkan kesalahan, dan fungsi mengembalikan bilangan bulat mengembalikan nol untuk menunjukkan keberhasilan atau bukan nol untuk menunjukkan kesalahan. Perhatikan bahwa "bukan nol" berarti hanya itu. Kecuali deskripsi fungsi mengatakan sebaliknya, jangan menguji nilai selain nol
if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ...Ketika suatu fungsi menghasilkan kesalahan, subbagian Kesalahan dari deskripsi fungsi mencantumkan jenis kesalahan yang mungkin terjadi. Anda dapat mengetahui mana yang terjadi dengan memanggil mysql_errno(). Representasi string dari kesalahan dapat diperoleh dengan memanggil mysql_error()
my_ulonglong mysql_affected_rows(MYSQL *mysql)
Mengembalikan jumlah baris yang diubah oleh UPDATE terakhir, dihapus oleh DELETE terakhir, atau disisipkan oleh pernyataan INSERT terakhir. Dapat dipanggil segera setelah mysql_query() untuk pernyataan UPDATE, DELETE, atau INSERT. Untuk pernyataan SELECT, mysql_affected_rows() berfungsi seperti mysql_num_rows()
Bilangan bulat yang lebih besar dari nol menunjukkan jumlah baris yang terpengaruh atau diambil. Nol menunjukkan bahwa tidak ada record yang diperbarui untuk pernyataan UPDATE, tidak ada baris yang cocok dengan klausa WHERE dalam kueri, atau bahwa belum ada kueri yang dieksekusi. -1 menunjukkan bahwa kueri mengembalikan kesalahan atau, untuk kueri SELECT, mysql_affected_rows( ) dipanggil sebelum memanggil mysql_store_result()
mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));_
Jika seseorang menentukan flag CLIENT_FOUND_ROWS saat menghubungkan ke mysqld, mysql_affected_rows() akan mengembalikan jumlah baris yang cocok dengan pernyataan WHERE untuk pernyataan UPDATE
Perhatikan bahwa ketika seseorang menggunakan perintah REPLACE, mysql_affected_rows() akan mengembalikan 2 jika baris baru menggantikan baris lama. Ini karena dalam kasus ini satu baris disisipkan dan duplikatnya dihapus
my_bool mysql_change_user(MYSQL *mysql, const char *pengguna, const char *kata sandi, const char *db)
Mengubah pengguna dan menyebabkan database yang ditentukan oleh db menjadi database default (saat ini) pada koneksi yang ditentukan oleh mysql. Dalam kueri selanjutnya, database ini adalah default untuk referensi tabel yang tidak menyertakan penentu database eksplisit
Fungsi ini diperkenalkan di MySQL Versi 3. 23. 3
mysql_change_user() gagal kecuali pengguna yang terhubung dapat diautentikasi atau jika dia tidak memiliki izin untuk menggunakan database. Dalam hal ini pengguna dan basis data tidak diubah
Parameter db dapat diatur ke NULL jika Anda tidak ingin memiliki database default
Nol untuk sukses. Bukan nol jika terjadi kesalahan
Hal yang sama yang bisa Anda dapatkan dari mysql_real_connect()
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
ER_UNKNOWN_COM_ERRORServer MySQL tidak mengimplementasikan perintah ini (mungkin server lama)
ER_ACCESS_DENIED_ERRORPengguna atau kata sandi salah
ER_BAD_DB_ERRORBasis data tidak ada
ER_DBACCESS_DENIED_ERRORPengguna tidak memiliki hak akses ke database
ER_WRONG_DB_NAMENama database terlalu panjang
if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }
mysql_character_set_name( )
const char *mysql_character_set_name(MYSQL *mysql)
Mengembalikan set karakter default untuk koneksi saat ini
Set karakter default
membatalkan mysql_close(MYSQL *mysql)
Menutup koneksi yang dibuka sebelumnya. mysql_close( ) juga membatalkan alokasi pegangan koneksi yang ditunjuk oleh mysql jika pegangan dialokasikan secara otomatis oleh mysql_init( ) atau mysql_connect( )
MYSQL *mysql_connect(MYSQL *mysql, const char *host, const char *pengguna, const char *passwd)
Fungsi ini sudah tidak digunakan lagi. Lebih baik menggunakan mysql_real_connect() sebagai gantinya
mysql_connect() mencoba membuat koneksi ke mesin database MySQL yang berjalan di host. mysql_connect( ) harus berhasil diselesaikan sebelum Anda dapat menjalankan salah satu fungsi API lainnya, kecuali mysql_get_client_info( )
Arti parameternya sama dengan parameter terkait untuk mysql_real_connect() dengan perbedaan bahwa parameter koneksi mungkin NULL. Dalam hal ini C API mengalokasikan memori untuk struktur koneksi secara otomatis dan membebaskannya saat Anda memanggil mysql_close(). Kerugian dari pendekatan ini adalah Anda tidak dapat mengambil pesan kesalahan jika koneksi gagal. (Untuk mendapatkan informasi kesalahan dari mysql_errno( ) atau mysql_error( ), Anda harus memberikan pointer MYSQL yang valid. )
Sama seperti untuk mysql_real_connect()
Sama seperti untuk mysql_real_connect()
int mysql_create_db(MYSQL *mysql, const char *db)
Membuat database yang dinamai dengan parameter db
Fungsi ini sudah tidak digunakan lagi. Lebih baik menggunakan mysql_query() untuk mengeluarkan pernyataan SQL CREATE DATABASE sebagai gantinya
Nol jika database berhasil dibuat. Bukan nol jika terjadi kesalahan
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
if(mysql_create_db(&mysql, "my_database")) { fprintf(stderr, "Failed to create new database. Error: %s\n", mysql_error(&mysql)); }_
membatalkan mysql_data_seek(MYSQL_RES *hasil, my_ulonglong offset)
Mencari baris arbitrer dalam kumpulan hasil kueri. Ini mengharuskan struktur kumpulan hasil berisi seluruh hasil kueri, jadi mysql_data_seek( ) hanya dapat digunakan bersama dengan mysql_store_result( ), bukan dengan mysql_use_result( )
Offset harus berupa nilai dalam rentang dari 0 hingga mysql_num_rows(result)-1
membatalkan mysql_debug(const char *debug)
Apakah DBUG_PUSH dengan string yang diberikan. mysql_debug() menggunakan pustaka debug Fred Fish. Untuk menggunakan fungsi ini, Anda harus mengkompilasi pustaka klien untuk mendukung proses debug. Lihat , dan Bagian D. 2
Panggilan berikut menyebabkan perpustakaan klien menghasilkan file pelacakan di if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ...0 pada mesin klien
mysql_debug("d:t:O,/tmp/client.trace");_int mysql_drop_db(MYSQL *mysql, const char *db)
Menjatuhkan database yang dinamai oleh parameter db
Fungsi ini sudah tidak digunakan lagi. Lebih baik menggunakan mysql_query() untuk mengeluarkan pernyataan SQL DROP DATABASE sebagai gantinya
Nol jika database berhasil dijatuhkan. Bukan nol jika terjadi kesalahan
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
if(mysql_drop_db(&mysql, "my_database")) fprintf(stderr, "Failed to drop the database: Error: %s\n", mysql_error(&mysql));_
int mysql_dump_debug_info(MYSQL *mysql)
Memerintahkan server untuk menulis beberapa informasi debug ke log. Pengguna yang terhubung harus memiliki hak istimewa proses agar ini berfungsi
Nol jika perintah berhasil. Bukan nol jika terjadi kesalahan
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
my_bool mysql_eof(MYSQL_RES *hasil)
Fungsi ini sudah tidak digunakan lagi. mysql_errno( ) atau mysql_error( ) dapat digunakan sebagai gantinya
mysql_eof() menentukan apakah baris terakhir dari kumpulan hasil telah dibaca
Jika Anda memperoleh rangkaian hasil dari panggilan yang berhasil ke mysql_store_result() , klien menerima seluruh rangkaian dalam satu operasi. Dalam hal ini, pengembalian NULL dari mysql_fetch_row( ) selalu berarti akhir dari rangkaian hasil telah tercapai dan tidak perlu memanggil mysql_eof( ). Saat digunakan dengan mysql_store_result( ), mysql_eof( ) akan selalu mengembalikan nilai true
Di sisi lain, jika Anda menggunakan mysql_use_result() untuk memulai pengambilan set hasil, baris set diperoleh dari server satu per satu saat Anda memanggil mysql_fetch_row() berulang kali. Karena kesalahan dapat terjadi pada koneksi selama proses ini, nilai pengembalian NULL dari mysql_fetch_row() tidak berarti akhir dari rangkaian hasil tercapai secara normal. Dalam hal ini, Anda dapat menggunakan mysql_eof() untuk menentukan apa yang terjadi. mysql_eof() mengembalikan nilai bukan nol jika akhir set hasil tercapai dan nol jika terjadi kesalahan
Secara historis, mysql_eof( ) mendahului fungsi kesalahan MySQL standar mysql_errno( ) dan mysql_error( ). Karena fungsi error tersebut memberikan informasi yang sama, penggunaannya lebih disukai daripada mysql_eof( ), yang sekarang sudah tidak digunakan lagi. (Faktanya, mereka memberikan lebih banyak informasi karena mysql_eof() hanya mengembalikan nilai boolean sedangkan fungsi kesalahan menunjukkan alasan kesalahan ketika terjadi. )
Nol jika tidak terjadi kesalahan. Bukan nol jika akhir dari set hasil telah tercapai
Contoh berikut menunjukkan bagaimana Anda dapat menggunakan mysql_eof()
mysql_query(&mysql,"SELECT * FROM some_table"); result = mysql_use_result(&mysql); while((row = mysql_fetch_row(result))) { // do something with data } if(!mysql_eof(result)) // mysql_fetch_row( ) failed due to an error { fprintf(stderr, "Error: %s\n", mysql_error(&mysql)); }Namun, Anda dapat mencapai efek yang sama dengan fungsi kesalahan standar MySQL
if (IS_NUM(field->type)) printf("Field is numeric\n");_0unsigned int mysql_errno(MYSQL *mysql)
Untuk koneksi yang ditentukan oleh mysql, mysql_errno() mengembalikan kode kesalahan untuk fungsi API yang terakhir dipanggil yang dapat berhasil atau gagal. Nilai pengembalian nol berarti tidak ada kesalahan yang terjadi. Nomor pesan kesalahan klien tercantum dalam file header MySQL ________3______1. Nomor pesan kesalahan server tercantum dalam if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ...2. Dalam distribusi sumber MySQL Anda dapat menemukan daftar lengkap pesan kesalahan dan nomor kesalahan dalam file if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ...3
Nilai kode kesalahan. Nol jika tidak terjadi kesalahan
char *mysql_error(MYSQL *mysql)
Untuk koneksi yang ditentukan oleh mysql, mysql_error() mengembalikan pesan kesalahan untuk fungsi API yang terakhir dipanggil yang bisa berhasil atau gagal. String kosong (" ") dikembalikan jika tidak terjadi kesalahan. Ini berarti dua tes berikut ini setara
if (IS_NUM(field->type)) printf("Field is numeric\n");_1Bahasa pesan kesalahan klien dapat diubah dengan mengkompilasi ulang pustaka klien MySQL. Saat ini Anda dapat memilih pesan kesalahan dalam beberapa bahasa berbeda. Melihat
String karakter yang menjelaskan kesalahan. String kosong jika tidak terjadi kesalahan
Anda harus menggunakan mysql_real_escape_string() sebagai gantinya
Fungsi ini identik dengan mysql_real_escape_string( ) kecuali bahwa mysql_real_escape_string( ) menggunakan penangan koneksi sebagai argumen pertamanya dan melepaskan string sesuai dengan set karakter saat ini. mysql_escape_string( ) tidak mengambil argumen koneksi dan tidak menghormati pengaturan charset saat ini
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *hasil)
Mengembalikan definisi satu kolom hasil yang ditetapkan sebagai struktur MYSQL_FIELD. Panggil fungsi ini berulang kali untuk mengambil informasi tentang semua kolom di kumpulan hasil. mysql_fetch_field( ) mengembalikan NULL ketika tidak ada lagi bidang yang tersisa
mysql_fetch_field( ) disetel ulang untuk mengembalikan informasi tentang bidang pertama setiap kali Anda menjalankan kueri SELECT baru. Bidang yang dikembalikan oleh mysql_fetch_field( ) juga dipengaruhi oleh panggilan ke mysql_field_seek( )
Jika Anda telah memanggil mysql_query( ) untuk melakukan SELECT pada tabel tetapi belum memanggil mysql_store_result( ), MySQL mengembalikan panjang gumpalan default (8K byte) jika Anda memanggil mysql_fetch_field( ) untuk menanyakan panjang bidang BLOB. (Ukuran 8K dipilih karena MySQL tidak mengetahui panjang maksimal untuk BLOB. Ini harus dibuat dapat dikonfigurasi kapan-kapan. ) Setelah Anda mengambil kumpulan hasil, field->max_length berisi panjang nilai terbesar untuk kolom ini dalam kueri tertentu
Struktur MYSQL_FIELD untuk kolom saat ini. NULL jika tidak ada kolom yang tersisa
if (IS_NUM(field->type)) printf("Field is numeric\n");_2
MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *hasil)
Mengembalikan array dari semua struktur MYSQL_FIELD untuk kumpulan hasil. Setiap struktur menyediakan definisi bidang untuk satu kolom dari kumpulan hasil
Array struktur MYSQL_FIELD untuk semua kolom dari kumpulan hasil
if (IS_NUM(field->type)) printf("Field is numeric\n");_3
mysql_fetch_field_direct()
MYSQL_FIELD *mysql_fetch_field_direct(MYSQL_RES *hasil, bidang int tidak ditandatangani)
Diberikan field nomor fieldnr untuk kolom dalam set hasil, kembalikan definisi field kolom itu sebagai struktur MYSQL_FIELD. Anda dapat menggunakan fungsi ini untuk mengambil definisi kolom arbitrer. Nilai fieldnr harus berkisar dari 0 hingga mysql_num_fields(result)-1
Struktur MYSQL_FIELD untuk kolom yang ditentukan
if (IS_NUM(field->type)) printf("Field is numeric\n");_4
unsigned long *mysql_fetch_lengths(MYSQL_RES *result)
Mengembalikan panjang kolom dari baris saat ini dalam kumpulan hasil. Jika Anda berencana menyalin nilai bidang, informasi panjang ini juga berguna untuk pengoptimalan karena Anda dapat menghindari pemanggilan strlen(). Selain itu, jika kumpulan hasil berisi data biner, Anda harus menggunakan fungsi ini untuk menentukan ukuran data karena strlen() mengembalikan hasil yang salah untuk setiap bidang yang berisi karakter null
Panjang kolom kosong dan kolom yang berisi nilai NULL adalah nol. Untuk melihat bagaimana membedakan kedua kasus ini, lihat deskripsi untuk mysql_fetch_row()
Larik bilangan bulat panjang tak bertanda yang mewakili ukuran setiap kolom (tidak termasuk karakter nol terminasi). NULL jika terjadi kesalahan
mysql_fetch_lengths( ) hanya valid untuk baris saat ini dari set hasil. Ini mengembalikan NULL jika Anda memanggilnya sebelum memanggil mysql_fetch_row() atau setelah mengambil semua baris dalam hasil
if (IS_NUM(field->type)) printf("Field is numeric\n");_5
MYSQL_ROW mysql_fetch_row(MYSQL_RES *hasil)
Mengambil baris berikutnya dari kumpulan hasil. Ketika digunakan setelah mysql_store_result() , mysql_fetch_row() mengembalikan NULL ketika tidak ada lagi baris untuk diambil. Ketika digunakan setelah mysql_use_result() , mysql_fetch_row() mengembalikan NULL ketika tidak ada lagi baris untuk diambil atau jika terjadi kesalahan
Jumlah nilai dalam baris diberikan oleh mysql_num_fields(result). Jika baris menyimpan nilai kembalian dari panggilan ke mysql_fetch_row( ), penunjuk ke nilai diakses sebagai baris[0] ke baris[mysql_num_fields(hasil)-1]. Nilai NULL pada baris ditunjukkan oleh pointer NULL
Panjang nilai bidang dalam baris dapat diperoleh dengan memanggil mysql_fetch_lengths(). Bidang kosong dan bidang yang berisi NULL keduanya memiliki panjang 0; . Jika penunjuk adalah NULL, bidangnya adalah NULL;
Struktur MYSQL_ROW untuk baris berikutnya. NULL jika tidak ada lagi baris untuk diambil atau jika terjadi kesalahan
CR_SERVER_LOST
Sambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
if (IS_NUM(field->type)) printf("Field is numeric\n");6
unsigned int mysql_field_count(MYSQL *mysql)
If you are using a version of MySQL earlier than Version 3. 22. 24, you should use unsigned int mysql_num_fields(MYSQL *mysql) instead
Returns the number of columns for the most recent query on the connection
The normal use of this function is when mysql_store_result( ) returned NULL (and thus you have no result set pointer). In this case, you can call mysql_field_count( ) to determine whether mysql_store_result( ) should have produced a non-empty result. This allows the client program to take proper action without knowing whether the query was a SELECT (or SELECT-like) statement. The following example illustrates how this may be done
.
An unsigned integer representing the number of fields in a result set
if (IS_NUM(field->type)) printf("Field is numeric\n");7
An alternative is to replace the mysql_field_count(&mysql) call with mysql_errno(&mysql). In this case, you are checking directly for an error from mysql_store_result( ) rather than inferring from the value of mysql_field_count( ) whether the statement was a SELECT
MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL_RES *result, MYSQL_FIELD_OFFSET offset)
Sets the field cursor to the given offset. The next call to mysql_fetch_field( ) will retrieve the field definition of the column associated with that offset
To seek to the beginning of a row, pass an offset value of zero
Nilai sebelumnya dari kursor bidang
MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES *result)
Returns the position of the field cursor used for the last mysql_fetch_field( ). This value can be used as an argument to mysql_field_seek( )
The current offset of the field cursor
void mysql_free_result(MYSQL_RES *result)
Frees the memory allocated for a result set by mysql_store_result( ), mysql_use_result( ), mysql_list_dbs( ), etc. When you are done with a result set, you must free the memory it uses by calling mysql_free_result( )
char *mysql_get_client_info(void)
Returns a string that represents the client library version
A character string that represents the MySQL client library version
char *mysql_get_host_info(MYSQL *mysql)
Returns a string describing the type of connection in use, including the server hostname
A character string representing the server hostname and the connection type
unsigned int mysql_get_proto_info(MYSQL *mysql)
Returns the protocol version used by the current connection
An unsigned integer representing the protocol version used by the current connection
char *mysql_get_server_info(MYSQL *mysql)
Returns a string that represents the server version number
A character string that represents the server version number
char *mysql_info(MYSQL *mysql)
Retrieves a string providing information about the most recently executed query, but only for the following statements. For other statements, mysql_info( ) returns NULL. The format of the string varies depending on the type of query. The numbers are illustrative only; the string will contain values appropriate for the query
INSERT INTO . SELECT
String format. Records. 100 Duplicates. 0 Warnings. 0
INSERT INTO . VALUES (. ),(. ),(. )String format. Records. 3 Duplicates. 0 Warnings. 0
LOAD DATA INFILEString format. Records. 1 Deleted. 0 Skipped. 0 Warnings. 0
ALTER TABLEString format. Records. 3 Duplicates. 0 Warnings. 0
UPDATEString format. Rows matched. 40 Changed. 40 Warnings. 0
Note that mysql_info( ) returns a non-NULL value for the INSERT . VALUES statement only if multiple value lists are specified in the statement
A character string representing additional information about the most recently executed query. NULL if no information is available for the query
MYSQL *mysql_init(MYSQL *mysql)
Mengalokasikan atau menginisialisasi objek MySQL yang cocok untuk mysql_real_connect(). If mysql is a NULL pointer, the function allocates, initialises, and returns a new object. Otherwise, the object is initialised and the address of the object is returned. If mysql_init( ) allocates a new object, it will be freed when mysql_close( ) is called to close the connection
An initialised MYSQL* handle. NULL if there was insufficient memory to allocate a new object
In case of insufficient memory, NULL is returned
my_ulonglong mysql_insert_id(MYSQL *mysql)
Returns the ID generated for an AUTO_INCREMENT column by the previous query. Use this function after you have performed an INSERT query into a table that contains an AUTO_INCREMENT field
Note that mysql_insert_id( ) returns 0 if the previous query does not generate an AUTO_INCREMENT value. If you need to save the value for later, be sure to call mysql_insert_id( ) immediately after the query that generates the value
mysql_insert_id( ) is updated after INSERT and UPDATE statements that generate an AUTO_INCREMENT value or that set a column value to LAST_INSERT_ID(expr). See
Also note that the value of the SQL LAST_INSERT_ID( ) function always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries because the value of that function is maintained in the server
The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value
int mysql_kill(MYSQL *mysql, unsigned long pid)
Asks the server to kill the thread specified by pid
Nol untuk sukses. Bukan nol jika terjadi kesalahan
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
MYSQL_RES *mysql_list_dbs(MYSQL *mysql, const char *wild)
Returns a result set consisting of database names on the server that match the simple regular expression specified by the wild parameter. wild may contain the wildcard characters if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ...4 or if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ...5, or may be a NULL pointer to match all databases. Calling mysql_list_dbs( ) is similar to executing the query SHOW databases [LIKE wild]
You must free the result set with mysql_free_result( )
A MYSQL_RES result set for success. NULL if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_OUT_OF_MEMORYHabis ingatan
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
MYSQL_RES *mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)
Mengembalikan kumpulan hasil yang terdiri dari nama bidang dalam tabel tertentu yang cocok dengan ekspresi reguler sederhana yang ditentukan oleh parameter liar. liar dapat berisi karakter wildcard if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ..._4 atau if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ...5, atau mungkin berupa penunjuk NULL untuk mencocokkan semua bidang. Memanggil mysql_list_fields() mirip dengan mengeksekusi kueri TAMPILKAN KOLOM DARI tbl_name [SEPERTI liar]
Perhatikan bahwa Anda disarankan untuk menggunakan SHOW COLUMNS FROM tbl_name daripada mysql_list_fields()
You must free the result set with mysql_free_result( )
A MYSQL_RES result set for success. NULL if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
MYSQL_RES *mysql_list_processes(MYSQL *mysql)
Mengembalikan kumpulan hasil yang menjelaskan utas server saat ini. Ini adalah jenis informasi yang sama seperti yang dilaporkan oleh daftar proses mysqladmin atau kueri SHOW PROCESSLIST
You must free the result set with mysql_free_result( )
A MYSQL_RES result set for success. NULL if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
MYSQL_RES *mysql_list_tables(MYSQL *mysql, const char *wild)
Mengembalikan kumpulan hasil yang terdiri dari nama tabel dalam database saat ini yang cocok dengan ekspresi reguler sederhana yang ditentukan oleh parameter liar. liar dapat berisi karakter wildcard if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ..._4 atau if (result) /* correct */ .. error ... if (result < 0) /* incorrect */ .. error ... if (result == -1) /* incorrect */ .. error ...5, atau mungkin berupa pointer NULL untuk mencocokkan semua tabel. Memanggil mysql_list_tables() mirip dengan mengeksekusi query SHOW tables [LIKE wild]
You must free the result set with mysql_free_result( )
A MYSQL_RES result set for success. NULL if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
unsigned int mysql_num_fields(MYSQL_RES *result)
atau
unsigned int mysql_num_fields(MYSQL *mysql)
The second form doesn’t work on MySQL Version 3. 22. 24 or newer. To pass a MYSQL* argument, you must use unsigned int mysql_field_count(MYSQL *mysql) instead
Mengembalikan jumlah kolom dalam kumpulan hasil
Note that you can get the number of columns either from a pointer to a result set or to a connection handle. You would use the connection handle if mysql_store_result( ) or mysql_use_result( ) returned NULL (and thus you have no result set pointer). In this case, you can call mysql_field_count( ) to determine whether mysql_store_result( ) should have produced a non-empty result. This allows the client program to take proper action without knowing whether or not the query was a SELECT (or SELECT-like) statement. The following example illustrates how this may be done
.
An unsigned integer representing the number of fields in a result set
if (IS_NUM(field->type)) printf("Field is numeric\n");8
An alternative (if you know that your query should have returned a result set) is to replace the mysql_errno(&mysql) call with a check if mysql_field_count(&mysql) is = 0. This will only happen if something went wrong
my_ulonglong mysql_num_rows(MYSQL_RES *result)
Returns the number of rows in the result set
The use of mysql_num_rows( ) depends on whether you use mysql_store_result( ) or mysql_use_result( ) to return the result set. If you use mysql_store_result( ), mysql_num_rows( ) may be called immediately. If you use mysql_use_result( ), mysql_num_rows( ) will not return the correct value until all the rows in the result set have been retrieved
Jumlah baris dalam kumpulan hasil
int mysql_options(MYSQL *mysql, enum mysql_option option, const char *arg)
Can be used to set extra connect options and affect behavior for a connection. This function may be called multiple times to set several options
mysql_options( ) should be called after mysql_init( ) and before mysql_connect( ) or mysql_real_connect( )
The option argument is the option that you want to set; the arg argument is the value for the option. If the option is an integer, arg should point to the value of the integer
Possible option values
Option
Argument type
Fungsi
MYSQL_OPT_CONNECT_TIMEOUT
unsigned int *
Connect timeout in seconds
MYSQL_OPT_COMPRESS
Not used
Use the compressed client/server protocol
MYSQL_OPT_LOCAL_INFILE
Optional pointer to uint
If no pointer is given or if pointer points to a nonzero unsigned int . = 0, the command LOAD LOCAL INFILE is enabled
MYSQL_OPT_NAMED_PIPE
Not used
Use named pipes to connect to a MySQL server on NT
MYSQL_INIT_COMMAND
char *
Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting
MYSQL_READ_DEFAULT_FILE
char *
Read options from the named option file instead of from mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));0
MYSQL_READ_DEFAULT_GROUP
char *
Read options from the named group from mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));0 or the file specified with MYSQL_READ_DEFAULT_FILE
Note that the group client is always read if you use MYSQL_READ_DEFAULT_FILE or MYSQL_READ_DEFAULT_GROUP
The specified group in the option file may contain the following options
Option
Keterangan
connect-timeout
Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer from the server
compress
Use the compressed client/server protocol
database
Connect to this database if no database was specified in the connect command
debug
Debug options
disable-local-infile
Disable use of LOAD DATA LOCAL
host
Default hostname
init-command
Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting
interactive-timeout
Same as specifying CLIENT_INTERACTIVE to mysql_real_connect( ). See
local-infile[=(0. 1)]
If no argument or argument . = 0, then enable use of LOAD DATA LOCAL
password
Default password
pipe
Use named pipes to connect to a MySQL server on NT
port
Default port number
return-found-rows
Tell mysql_info( ) to return found rows instead of updated rows when using UPDATE
socket
Nomor soket default
user
Default user
Note that timeout has been replaced by connect-timeout, but timeout will still work for a while
For more information about option files, see
Zero for success. Non-zero if you used an unknown option
if (IS_NUM(field->type)) printf("Field is numeric\n");9
This requests that the client use the compressed client/server protocol and read the additional options from the odbc section in the mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));0 file
int mysql_ping(MYSQL *mysql)
Checks whether the connection to the server is working. If it has gone down, an automatic reconnection is attempted
This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and to reconnect if necessary
Zero if the server is alive. Non-zero if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
int mysql_query(MYSQL *mysql, const char *query)
Executes the SQL query pointed to by the null-terminated string query. The query must consist of a single SQL statement. You should not add a terminating semicolon (mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));3) or \g to the statement
mysql_query( ) cannot be used for queries that contain binary data; you should use mysql_real_query( ) instead. (Binary data may contain the mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));4 character, which mysql_query( ) interprets as the end of the query string. )
If you want to know if the query should return a result set, you can use mysql_field_count( ) to check for this. See
Zero if the query was successful. Non-zero if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned int client_flag)
mysql_real_connect( ) attempts to establish a connection to a MySQL database engine running on host. mysql_real_connect( ) must complete successfully before you can execute any of the other API functions, with the exception of mysql_get_client_info( )
Parameter ditentukan sebagai berikut
Parameter pertama harus berupa alamat dari struktur MYSQL yang ada. Before calling mysql_real_connect( ) you must call mysql_init( ) to initialise the MYSQL structure. You can change a lot of connect options with the mysql_options( ) call. See
The value of host may be either a hostname or an IP address. If host is NULL or the string "localhost", a connection to the local host is assumed. If the OS supports sockets (Unix) or named pipes (Windows), they are used instead of TCP/IP to connect to the server
The user parameter contains the user’s MySQL login ID. Jika pengguna NULL, pengguna saat ini diasumsikan. Di bawah Unix, ini adalah nama login saat ini. Under Windows ODBC, the current username must be specified explicitly. See
The passwd parameter contains the password for user. If passwd is NULL, only entries in the user table for the user that have a blank (empty) password field will be checked for a match. This allows the database administrator to set up the MySQL privilege system in such a way that users get different privileges depending on whether they have specified a password
Note. do not attempt to encrypt the password before calling mysql_real_connect( ); password encryption is handled automatically by the client API
db is the database name. If db is not NULL, the connection will set the default database to this value
If port is not 0, the value will be used as the port number for the TCP/IP connection. Note that the host parameter determines the type of the connection
If unix_socket is not NULL, the string specifies the socket or named pipe that should be used. Note that the host parameter determines the type of the connection
The value of client_flag is usually 0, but can be set to a combination of the following flags in very special circumstances
Flag name
Deskripsi bendera
CLIENT_COMPRESS
Use compression protocol
CLIENT_FOUND_ROWS
Return the number of found (matched) rows, not the number of affected rows
CLIENT_IGNORE_SPACE
Izinkan spasi setelah nama fungsi. Makes all function names reserved words
CLIENT_INTERACTIVE
Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection
CLIENT_NO_SCHEMA
Don’t allow the db_name. tbl_name. col_name syntax. This is for ODBC. It causes the parser to generate an error if you use that syntax, which is useful for trapping bugs in some ODBC programs
CLIENT_ODBC
The client is an ODBC client. This changes mysqld to be more ODBC-friendly
CLIENT_SSL
Use SSL (encrypted protocol)
A MYSQL* connection handle if the connection was successful, NULL if the connection was unsuccessful. For a successful connection, the return value is the same as the value of the first parameter
CR_CONN_HOST_ERROR
Failed to connect to the MySQL server
CR_CONNECTION_ERRORFailed to connect to the local MySQL server
CR_IPSOCK_ERRORFailed to create an IP socket
CR_OUT_OF_MEMORYHabis ingatan
CR_SOCKET_CREATE_ERRORFailed to create a Unix socket
CR_UNKNOWN_HOSTFailed to find the IP address for the hostname
CR_VERSION_ERRORA protocol mismatch resulted from attempting to connect to a server with a client library that uses a different protocol version. This can happen if you use a very old client library to connect to a new server that wasn’t started with the --old-protocol option
CR_NAMEDPIPEOPEN_ERRORFailed to create a named pipe on Windows
CR_NAMEDPIPEWAIT_ERRORFailed to wait for a named pipe on Windows
CR_NAMEDPIPESETSTATE_ERRORFailed to get a pipe handler on Windows
CR_SERVER_LOSTIf connect_timeout > 0 and it took longer than connect_timeout seconds to connect to the server or if the server died while executing the init-command
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");0
By using mysql_options( ) the MySQL library will read the [client] and your_prog_name sections in the mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));0 file, which will ensure that your program will work, even if someone has set up MySQL in some non-standard way
Note that upon connection, mysql_real_connect( ) sets the reconnect flag (part of the MYSQL structure) to a value of 1. This flag indicates, in the event that a query cannot be performed because of a lost connection, that you should try reconnecting to the server before giving up
mysql_real_escape_string()
unsigned long mysql_real_escape_string(MYSQL *mysql, char *to, const char *from, unsigned long length)
This function is used to create a legal SQL string that you can use in an SQL statement. See
The string in from is encoded to an escaped SQL string, taking into account the current character set of the connection. The result is placed in to and a terminating null byte is appended. Characters encoded are NUL (ASCII 0), mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));6, mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));7, mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));8, ', “, and Control-Z (see )
The string pointed to by from must be length bytes long. You must allocate the to buffer to be at least length*2+1 bytes long. (In the worse case, each character may need to be encoded as using two bytes, and you need room for the terminating null byte. ) When mysql_escape_string( ) returns, the contents of to will be a null-terminated string. The return value is the length of the encoded string, not including the terminating null character
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");1
The strmov( ) function used in the example is included in the mysqlclient library and works like strcpy( ) but returns a pointer to the terminating null of the first parameter
The length of the value placed into to, not including the terminating null character
int mysql_real_query(MYSQL *mysql, const char *query, unsigned long length)
Executes the SQL query pointed to by query, which should be a string length bytes long. The query must consist of a single SQL statement. Anda tidak boleh menambahkan titik koma akhir (mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));3) atau \g ke pernyataan
You must use mysql_real_query( ) rather than mysql_query( ) for queries that contain binary data because binary data may contain the mysql_query(&mysql,"UPDATE products SET cost=cost*1.25 WHERE group=10"); printf("%ld products updated",(long) mysql_affected_rows(&mysql));4 character. In addition, mysql_real_query( ) is faster than mysql_query( ) because it does not call strlen( ) on the query string
If you want to know whether the query should return a result set, you can use mysql_field_count( ) to check for this. See
Zero if the query was successful. Non-zero if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
int mysql_reload(MYSQL *mysql)
Asks the MySQL server to reload the grant tables. The connected user must have the reload privilege
This function is deprecated. It is preferable to use mysql_query( ) to issue a SQL FLUSH PRIVILEGES statement instead
Nol untuk sukses. Bukan nol jika terjadi kesalahan
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
Sambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset)
Sets the row cursor to an arbitrary row in a query result set. This requires that the result set structure contains the entire result of the query, so mysql_row_seek( ) may be used in conjunction only with mysql_store_result( ), not with mysql_use_result( )
The offset should be a value returned from a call to mysql_row_tell( ) or to mysql_row_seek( ). This value is not simply a row number; if you want to seek to a row within a result set using a row number, use mysql_data_seek( ) instead
The previous value of the row cursor. This value may be passed to a subsequent call to mysql_row_seek( )
MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result)
Returns the current position of the row cursor for the last mysql_fetch_row( ). This value can be used as an argument to mysql_row_seek( )
You should use mysql_row_tell( ) only after mysql_store_result( ), not after mysql_use_result( )
The current offset of the row cursor
int mysql_select_db(MYSQL *mysql, const char *db)
Causes the database specified by db to become the default (current) database on the connection specified by mysql. In subsequent queries, this database is the default for table references that do not include an explicit database specifier
mysql_select_db( ) fails unless the connected user can be authenticated as having permission to use the database
Nol untuk sukses. Bukan nol jika terjadi kesalahan
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
int mysql_shutdown(MYSQL *mysql)
Asks the database server to shut down. The connected user must have shutdown privileges
Nol untuk sukses. Bukan nol jika terjadi kesalahan
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
char *mysql_stat(MYSQL *mysql)
Returns a character string containing information similar to that provided by the mysqladmin status command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables
A character string describing the server status. NULL if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
MYSQL_RES *mysql_store_result(MYSQL *mysql)
You must call mysql_store_result( ) or mysql_use_result( ) for every query that successfully retrieves data (SELECT, SHOW, DESCRIBE, EXPLAIN)
You don’t have to call mysql_store_result( ) or mysql_use_result( ) for other queries, but it will not do any harm or cause any notable performance if you call mysql_store_result( ) in all cases. You can detect if the query didn’t have a result set by checking if mysql_store_result( ) returns 0 (more about this later)
If you want to know whether the query should return a result set, you can use mysql_field_count( ) to check for this. See
mysql_store_result( ) reads the entire result of a query to the client, allocates a MYSQL_RES structure, and places the result into this structure
mysql_store_result( ) returns a null pointer if the query didn’t return a result set (if the query was, for example, an INSERT statement)
mysql_store_result( ) also returns a null pointer if reading of the result set failed. Anda dapat memeriksa apakah Anda mendapat kesalahan dengan memeriksa apakah mysql_error( ) tidak mengembalikan penunjuk nol, jika mysql_errno( ) mengembalikan 0, atau jika mysql_field_count( ) mengembalikan 0
An empty result set is returned if there are no rows returned. (An empty result set differs from a null pointer as a return value. )
Once you have called mysql_store_result( ) and got a result back that isn’t a null pointer, you may call mysql_num_rows( ) to find out how many rows are in the result set
You can call mysql_fetch_row( ) to fetch rows from the result set, or mysql_row_seek( ) and mysql_row_tell( ) to obtain or set the current row position within the result set
You must call mysql_free_result( ) once you are done with the result set
.
A MYSQL_RES result structure with the results. NULL if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_OUT_OF_MEMORYHabis ingatan
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
unsigned long mysql_thread_id(MYSQL *mysql)
Returns the thread ID of the current connection. This value can be used as an argument to mysql_kill( ) to kill the thread
If the connection is lost and you reconnect with mysql_ping( ), the thread ID will change. This means you should not get the thread ID and store it for later. You should get it when you need it
The thread ID of the current connection
MYSQL_RES *mysql_use_result(MYSQL *mysql)
You must call mysql_store_result( ) or mysql_use_result( ) for every query that successfully retrieves data (SELECT, SHOW, DESCRIBE, EXPLAIN)
mysql_use_result( ) initiates a result set retrieval but does not actually read the result set into the client like mysql_store_result( ) does. Instead, each row must be retrieved individually by making calls to mysql_fetch_row( ). This reads the result of a query directly from the server without storing it in a temporary table or local buffer, which is somewhat faster and uses much less memory than mysql_store_result( ). The client will only allocate memory for the current row and a communication buffer that may grow up to max_allowed_packet bytes
Di sisi lain, Anda tidak boleh menggunakan mysql_use_result() jika Anda melakukan banyak pemrosesan untuk setiap baris di sisi klien, atau jika output dikirim ke layar tempat pengguna dapat mengetik ^S (stop scroll . This will tie up the server and prevent other threads from updating any tables from which the data is being fetched
When using mysql_use_result( ), you must execute mysql_fetch_row( ) until a NULL value is returned, otherwise, the unfetched rows will be returned as part of the result set for your next query. The C API will give the error Commands out of sync; you can't run this command now if you forget to do this
You may not use mysql_data_seek( ), mysql_row_seek( ), mysql_row_tell( ), mysql_num_rows( ), or mysql_affected_rows( ) with a result returned from mysql_use_result( ), nor may you issue other queries until the mysql_use_result( ) has finished. (However, after you have fetched all the rows, mysql_num_rows( ) will accurately return the number of rows fetched. )
You must call mysql_free_result( ) once you are done with the result set
A MYSQL_RES result structure. NULL if an error occurred
CR_COMMANDS_OUT_OF_SYNC
Perintah dijalankan dalam urutan yang tidak tepat
CR_OUT_OF_MEMORYHabis ingatan
CR_SERVER_GONE_ERRORServer MySQL telah hilang
CR_SERVER_LOSTSambungan ke server terputus selama kueri
CR_UNKNOWN_ERRORTerjadi kesalahan yang tidak diketahui
C Threaded Function Descriptions
You need to use the following functions when you want to create a threaded client. See
This function needs to be called once in the program before calling any MySQL function. This initialises some global variables that MySQL needs. If you are using a thread-safe client library, this will also call mysql_thread_init( ) for this thread
This is automatically called by mysql_init( ), mysql_server_init( ), and mysql_connect( )
my_bool mysql_thread_init(void)
This function needs to be called for each created thread to initialise thread-specific variables
This is automatically called by my_init( ) and mysql_connect( )
void mysql_thread_end(void)
This function needs to be called before calling pthread_exit( ) to free memory allocated by mysql_thread_init( )
Note that this function is not invoked automatically by the client library. It must be called explicitly to avoid a memory leak
unsigned int mysql_thread_safe(void)
This function indicates whether the client is compiled as thread-safe
1 is the client is thread-safe, 0 otherwise
C Embedded Server Function Descriptions
You must use the following functions if you want to allow your application to be linked against the embedded MySQL server library. See
If the program is linked with -lmysqlclient instead of -lmysqld, these functions do nothing. This makes it possible to choose between using the embedded MySQL server and a stand-alone server without modifying any code
int mysql_server_init(int argc, char **argv, char **groups)
This function must be called once in the program before calling any other MySQL function. It starts up the server and initialises any subsystems (mysys, InnoDB, etc. ) that the server uses. If this function is not called, the program will crash. If you are using the DBUG package that comes with MySQL, you should call this after you have called MY_INIT( )
The argc and argv arguments are analogous to the arguments to main( ). The first element of argv is ignored (it typically contains the program name). For convenience, argc may be 0 (zero) if there are no command-line arguments for the server
The NULL-terminated list of strings in groups selects which groups in the option files will be active. See . For convenience, groups may be NULL, in which case the [server] and [emedded] groups will be active
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");2
0 if okay, 1 if an error occurred
void mysql_server_end(void)
This function must be called once in the program after all other MySQL functions. It shuts down the embedded server
Common Questions and Problems When Using the C API
Why Is It that After mysql_query( ) Returns Success, mysql_store_result( ) Sometimes Returns NULL?
It is possible for mysql_store_result( ) to return NULL following a successful call to mysql_query( ). When this happens, it means one of the following conditions occurred
There was a malloc( ) failure (for example, if the result set was too large)
The data couldn’t be read (an error occurred on the connection)
The query returned no data (for example, it was an INSERT, UPDATE, or DELETE)
You can always check whether the statement should have produced a non-empty result by calling mysql_field_count( ). If mysql_field_count( ) returns zero, the result is empty and the last query was a statement that does not return values (for example, an INSERT or a DELETE). If mysql_field_count( ) returns a non-zero value, the statement should have produced a non-empty result. See the description of the mysql_field_count( ) function for an example
Anda dapat menguji kesalahan dengan memanggil mysql_error( ) atau mysql_errno( )
What results can I get from a query?
In addition to the result set returned by a query, you can also get the following information
mysql_affected_rows( ) returns the number of rows affected by the last query when doing an INSERT, UPDATE, or DELETE. An exception is that if DELETE is used without a WHERE clause, the table is re-created empty, which is much faster. In this case, mysql_affected_rows( ) returns zero for the number of records affected
mysql_num_rows( ) returns the number of rows in a result set. With mysql_store_result( ), mysql_num_rows( ) may be called as soon as mysql_store_result( ) returns. With mysql_use_result( ), mysql_num_rows( ) may be called only after you have fetched all the rows with mysql_fetch_row( )
mysql_insert_id( ) returns the ID generated by the last query that inserted a row into a table with an AUTO_INCREMENT index. See
Some queries (LOAD DATA INFILE . , INSERT INTO . SELECT . , UPDATE) return additional information. The result is returned by mysql_info( ). See the description for mysql_info( ) for the format of the string that it returns. mysql_info( ) returns a NULL pointer if there is no additional information
How can I get the unique ID for the last inserted row?
If you insert a record in a table containing a column that has the AUTO_INCREMENT attribute, you can get the most recently generated ID by calling the mysql_insert_id( ) function
You can also retrieve the ID by using the LAST_INSERT_ID( ) function in a query string that you pass to mysql_query( )
You can check if an AUTO_INCREMENT index is used by executing the following code. This also checks if the query was an INSERT with an AUTO_INCREMENT index
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");3The most recently generated ID is maintained in the server on a per-connection basis. It will not be changed by another client. It will not even be changed if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL and not 0)
If you want to use the ID that was generated for one table and insert it into a second table, you can use SQL statements like these
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");4Problems linking with the C API
When linking with the C API, the following errors may occur on some systems
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");5If this happens on your system, you must include the math library by adding -lm to the end of the compile/link line
If you compile MySQL clients that you’ve written yourself or that you obtain from a third-party, they must be linked using the -lmysqlclient -lz option on the link command. You may also need to specify a -L option to tell the linker where to find the library. For example, if the library is installed in if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }1, use -L/usr/local/mysql/lib -lmysqlclient -lz on the link command
Untuk klien yang menggunakan file header MySQL, Anda mungkin perlu menentukan opsi -I saat mengompilasinya (misalnya, -I/usr/local/mysql/include), sehingga kompiler dapat menemukan file header
How to Make a Threaded Client
The client library is almost thread-safe. The biggest problem is that the subroutines in if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }2 that read from sockets are not interrupt-safe. This was done with the thought that you might want to have your own alarm that can break a long read to a server. If you install interrupt handlers for the SIGPIPE interrupt, the socket handling should be thread-safe
In the older binaries we distribute on our web site (http. // www. mysql. com/), the client libraries are not normally compiled with the thread-safe option (the Windows binaries are, by default, compiled to be thread-safe). Distribusi biner yang lebih baru harus memiliki pustaka klien normal dan thread-safe
Untuk mendapatkan klien berulir di mana Anda dapat mengganggu klien dari utas lain dan mengatur waktu tunggu saat berbicara dengan server MySQL, Anda harus menggunakan pustaka -lmysys, -lstring, dan -ldbug dan net_serv. o code that the server uses
If you don’t need interrupts or timeouts, you can just compile a thread-safe client library (mysqlclient_r) and use this. See Section 8. 4. In this case you don’t have to worry about the net_serv. o object file or the other MySQL libraries
When using a threaded client and you want to use timeouts and interrupts, you can make great use of the routines in the if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }3 file. Jika Anda menggunakan rutinitas dari pustaka mysys, satu-satunya hal yang harus Anda ingat adalah memanggil my_init() terlebih dahulu. See
All functions except mysql_real_connect( ) are, by default, thread-safe. The following notes describe how to compile a thread-safe client library and use it in a thread-safe manner. (These notes for mysql_real_connect( ) actually apply to mysql_connect( ) as well, but because mysql_connect( ) is deprecated, you should be using mysql_real_connect( ) anyway. )
To make mysql_real_connect( ) thread-safe, you must recompile the client library with this command
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");6This will create a thread-safe client library libmysqlclient_r. --enable-thread-safe-client. This library is thread-safe per connection. You can let two threads share the same connection with the following caveats
Two threads can’t send a query to the MySQL server at the same time on the same connection. In particular, you have to ensure that between a mysql_query( ) and mysql_store_result( ) no other thread is using the same connection
Many threads can access different result sets that are retrieved with mysql_store_result( )
If you use mysql_use_result, you have to ensure that no other thread is using the same connection until the result set is closed. However, it really is best for threaded clients that share the same connection to use mysql_store_result( )
If you want to use multiple threads on the same connection, you must have a mutex lock around your mysql_query( ) and mysql_store_result( ) call combination. Once mysql_store_result( ) is ready, the lock can be released and other threads may query the same connection
If you program with POSIX threads, you can use pthread_mutex_lock( ) and pthread_mutex_unlock( ) to establish and release a mutex lock
You need to know the following if you have a thread that is calling MySQL functions that did not create the connection to the MySQL database
When you call mysql_init( ) or mysql_connect( ), MySQL will create a thread-specific variable for the thread that is used by the debug library (among other things)
If you call a MySQL function, before the thread has called mysql_init( ) or mysql_connect( ), the thread will not have the necessary thread-specific variables in place and you are likely to end up with a core dump sooner or later
The get things to work smoothly you have to do the following
Call my_init( ) at the start of your program if it calls any other MySQL function before calling mysql_real_connect( )
Call mysql_thread_init( ) in the thread handler before calling any MySQL function
In the thread, call mysql_thread_end( ) before calling pthread_exit( ). This will free the memory used by MySQL thread-specific variables
You may get some errors because of undefined symbols when linking your client with libmysqlclient_r. In most cases this is because you haven’t included the thread libraries on the link/compile line
libmysqld, the Embedded MySQL Server Library
Overview of the embedded MySQL server library
The embedded MySQL server library makes it possible to run a full-featured MySQL server inside the client application. The main benefits are increased speed and simpler management for embedded applications
The API is identical for the embedded MySQL version and the client/server version. To change an old threaded application to use the embedded library, you normally only have to add calls to the following functions
Fungsi
When to call
mysql_server_init( )
Should be called before any other MySQL function is called, preferably early in the main( ) function
mysql_server_end( )
Should be called before your program exits
mysql_thread_init( )
Should be called in each thread you create that will access MySQL
mysql_thread_end( )
Should be called before calling pthread_exit( )
Then you must link your code with libmysqld. a instead of libmysqlclient. a
The preceding mysql_server_xxx functions are also included in libmysqlclient. a to allow you to change between the embedded and the client/server version by just linking your application with the right library. See
Compiling programs with libmysqld
To get a libmysqld library you should configure MySQL with the --with-embedded-server option
When you link your program with libmysqld, you must also include the system-specific pthread libraries and some libraries that the MySQL server uses. You can get the full list of libraries by executing mysql_config --libmysqld-libs
The correct flags for compiling and linking a threaded program must be used, even if you do not directly call any thread functions in your code
Restrictions when using the embedded MySQL server
The embedded server has the following limitations
No support for ISAM tables. (This is mainly done to make the library smaller. )
No UDF functions
No stack trace on core dump
Tidak ada dukungan RAID internal. (This is not normally needed, as most OSes nowadays have support for big files. )
You can set this up as a server or a master (no replication)
You can’t connect to the embedded server from an outside process with sockets or TCP/IP
Some of these limitations can be changed by editing the if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }4 include file and recompiling MySQL
Using option files with the embedded server
The following is the recommended way to use option files to make it easy to switch between a client/server application and one where MySQL is embedded. See
Put common options in the [server] section. These will be read by both MySQL versions
Put client/server-specific options in the [mysqld] section
Put embedded MySQL-specific options in the [embedded] section
Put application-specific options in the [ApplicationName_SERVER] section
Things left to do in embedded server (TODO)
Currently we only provide a static version of the mysqld library. In the future we will also provide a shared library for this
We are going to provide options to leave out some parts of MySQL to make the library smaller
There is still a lot of speed optimisation to do
Errors are written to stderr. We will add an option to specify a filename for these
We have to change InnoDB to not be so verbose when used in the embedded version
A simple embedded server example
This example program and makefile should work without any changes on a Linux or FreeBSD system. For other operating systems, minor changes will be needed. This example is designed to give enough details to understand the problem, without the clutter that is a necessary part of a real application
To try out the example, create a if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }5 directory at the same level as the mysql-4. 0 source directory. Simpan sumber if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }_6 dan if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }7 di direktori, dan jalankan GNU if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }8 dari dalam direktori if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }5
if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }6
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");7if (mysql_change_user(&mysql, "user", "password", "new_database")) { fprintf(stderr, "Failed to change user. Error: %s\n", mysql_error(&mysql)); }7
if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");8if (field->flags & NOT_NULL_FLAG) printf("Field can't be null\n");9Licensing the embedded server
The MySQL source code is covered by the GNU GPL license (see http. //www. mysql. com/doc/G/P/GPL-license. html). Salah satu akibatnya adalah setiap program yang menyertakan, dengan menghubungkan dengan libmysqld, kode sumber MySQL harus dirilis sebagai perangkat lunak bebas (di bawah lisensi yang kompatibel dengan GPL)
Kami mendorong semua orang untuk mempromosikan perangkat lunak gratis dengan merilis kode di bawah GPL atau lisensi yang kompatibel. Bagi mereka yang tidak dapat melakukan ini, opsi lainnya adalah membeli lisensi komersial untuk kode MySQL dari MySQL AB. Untuk detailnya, silakan lihat