Advertisement
Guest User

mysql example for gtavmp

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