0 like 0 dislike
1 view
in Ruby by anonymous Bilge (165k points)
ruby ile mysql sunucuya bağlanma scripti

4 Answers

0 like 0 dislike
by anonymous Bilge (165k points)
require 'mysql2'

begin
  # DB ayarlarını oluşturalım
  host = String('127.0.0.1')
  database = String('km')
  username = String('root')
  password = String('q1')

  # Bağlantı nesnemiz
  client = Mysql2::Client.new(:host => host, :username => username, :database => database, :password => password)
  puts 'Successfully created connection to database.'

  # Data okuyalım
  resultSet = client.query('SELECT * from user;')
  resultSet.each do |row|
    puts 'Data row = (%s, %s, %s)' % [row['id'], row['name'], row['quantity']]
  end
  puts 'Read ' + resultSet.count.to_s + ' row(s).'

# Hata olursa
rescue Exception => e
  puts e.message

# Bağlantıyı kapatıyoruz
ensure
  client.close if client
  puts 'Done.'
end
0 like 0 dislike
by anonymous Bilge (165k points)
require 'mysql2'

begin
  host = String('127.0.0.1')
  database = String('km')
  username = String('root')
  password = String('q1')

  client = Mysql2::Client.new(:host => host, :username => username, :database => database, :password => password)
  puts 'Successfully created connection to database.'

  # Update data
  client.query('UPDATE user SET last_name="tester" WHERE id=1')
  puts 'Updated 1 row of data.'

rescue Exception => e
  puts e.message
  
ensure
  client.close if client
  puts 'Done.'
end
0 like 0 dislike
by anonymous Bilge (165k points)

Veri silme;

# Delete data
resultSet = client.query('DELETE FROM inventory WHERE name = %s;' % ['\'orange\''])
puts 'Deleted 1 row.'
0 like 0 dislike
by anonymous Bilge (165k points)

Tablo oluşturma;

client.query('DROP TABLE IF EXISTS stock;')
puts 'Finished dropping table (if existed).'

# Drop previous table of same name if one exists.
client.query('CREATE TABLE stock (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);')
puts 'Finished creating table.'
client.query("INSERT INTO inventory VALUES(1, 'abc', 1)")
client.query("INSERT INTO inventory VALUES(2, 'cde', 2)")
client.query("INSERT INTO inventory VALUES(3, 'efb', 3)")
puts 'Inserted 3 rows of data.'
...