Advertisement
Guest User

gtavmp

a guest
Jan 15th, 2016
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. using System;
  2. using V_MP.Server.API;
  3.  
  4. using MySql.Data;
  5. using MySql.Data.MySqlClient; // <- both of these MUST BE included
  6.  
  7. namespace MySQLExample{
  8.     public class Example : APIScript{
  9.         public override void OnChatCommand(User player, string command){
  10.             string[] cmd = command.Split(' '); // had a bug here, fixed now
  11.             if(cmd[0] == "/test"){
  12.                 try{ // a lot of mysql function throw exceptions, so it's recommended to use try-catch statement
  13.                     MySqlConnection connection = new MySqlConnection(); //Creates a new connection instance
  14.                     connection.ConnectionString = "server='localhost'; uid='your username'; pwd='your password'; database='database name'"; // change these depending on your setup!
  15.                     connection.Open(); // Opens connection
  16.  
  17.                     //INSERT - same with delete for example
  18.                     string username = "priitkaard"; //Your variables.
  19.                     string password = "testingmysql";
  20.                     MySqlCommand comm = connection.CreateCommand(); // command instance
  21.                     comm.CommandText = "INSERT INTO users(username, password) VALUES('"+username+"', '"+password+"')"; // query
  22.                     comm.ExecuteNonQuery();
  23.                     // done
  24.  
  25.                     //SELECT
  26.                     comm.CommandText = "SELECT password FROM users WHERE username='priitkaard'"; // why would you need such query, I have no idea :D
  27.                     MySqlDataReader reader = comm.ExecuteReader(); // creates a reader instance to get data
  28.                     string passw;
  29.                     while(reader.Read()){ // this.Read() returns boolean, so if there is something to read - true, otherwise false
  30.                         passw = reader.GetString(0);
  31.                     }
  32.                    
  33.                     reader.Close(); //close reader
  34.                     connection.Close(); // close mysql connection.
  35.                 }catch(Exception){
  36.                     SendMessageToPlayer(player, "System", "Failed to initialise MySql...");
  37.                 }
  38.             }
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement