Search the Community
Showing results for tags 'mysql'.
-
How to create a database and save a player's coordinates in it Hello. As a beginner I had lots of trouble finding a MySQL appropriate tutorial for beginners in development. I spent days learning how to create a basic table and save records in it. I decided to create this tutorial so that no one has to go throught what I went. This tutorial is divided in X parts. Feel free to jump ahead if you already to know how to do some. Index Downloading MySQL and MySQL Workbench Installing MySQL Driver Creating a database Connecting to the database and creating a table in it Manipulating the table 1- Installing MySQL and MySQL Workbench For you to be able to save databases and work with them you must first install MySQL and MySQL Workbench. Firstly, go to https://www.mysql.com/downloads/. Now, follow the steps on this video: https://www.youtube.com/watch?v=GIRcpjg-3Eg. I won't do a tutorial on how to install MySQL as it is to complex and very standart to everyone. 2- Installing MySQL Driver After installing MySQL we can access it by using Node.js. This tutorial will use the "mysql" module, downloaded from NPM. To download and install the "mysql" module, open the Command Terminal (go to your search bar and type 'cmd') and execute the following: C:\Users\Your Name>npm install mysql 3- Creating a database If you corretly followed the video above mentioned, you should have something like this once you open your MySQL Workbench: https://imgur.com/wSHrWr0 https://imgur.com/wSHrWr0 You want to press on Local instance MySQL80 or on any other connection you have. Once you do, the following page will open: https://imgur.com/vzSUhvS Right click on the left side box named Schemas and click 'Create Schema': https://imgur.com/rPg6RVi Name it 'rpg' (or whatever you want, just pay attention on the future steps) and click Apply twice and Finish. https://imgur.com/c1CrPwA Nice. Your database has been created. Now, we must connect to it. 4- Connecting to the database and creating a table in it To connect to a database, create a file on your server-files folder named connection.js. Once you create one go to your index.js and add in it the following: require('./connection.js') This will make your server know this file exists and run the code in it. Now, back to connection.js, type the following: var mysql = require('mysql'); With the first line, we are now importing the 'mysql' module to the file. Now, in the same file, type this: const con = mysql.createConnection({ host:'127.0.0.1', // host of server user:'user', // MySQL user password:'password', // MySQL password database: "rpg" }); With this code we are connecting to the database you host. Make sure to replace the user, the password and the database with whatever you had chosen in the previous steps. After connecting to the database, we can now manipulate it. Firstly, we'll create a table. The table can be created on MySQL Workbench or on the javascript file. If you create it on the file, it will try to create it everytime you open your ragemp-server, but it will return an innofensive error if it already exists. I'll create in on the file. Type the following: var sql = "CREATE TABLE players (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, scID int NOT NULL UNIQUE, posX int NOT NULL, posY int NOT NULL, posZ int NOT NULL)"; con.query(sql, function (err, result) { if (err) { console.log('The following error happened while creating [players]: ' + err); throw err; } console.log("[players] has been created"); }); With the code above we've just created a table called 'players' which has 5 columns: 'id', 'scID', 'posX', 'posY', 'posZ'. As you can see, all of them are integers, which means they only accept numbers. If you try to add 'banana' to 'posX', you'll get an error. Also, all of them are NOT NULL, which means that there must be a value in them, they can't be empty, or you'll also get an error. 'scID' is unique, which means that the same data can't be repeated twice. Finally, 'ID' is a Primary Key, which is a mix between NOT NULL and UNIQUE. It uniquely identifies each record in a table. It is also AUTO_INCREMENT, which means a new number will be automatically generated when a new record is inserted into a table. After typing it, open your console. You received the following log: "[players] has been created". It obviously confirms that the table has been created. If you close your console and open it again, you'll instead receive this log: "The following error happened while creating [players]: Error: ER_TABLE_EXISTS_ERROR: Table 'players' already exists". That means that the table couldn't be created because it already exists. There's nothing wrong with the error. You can change it so the server doesn't try to create a table if it already exists, but I'll just leave it be. Now that our table is created, we want to manipulate it, but first make sure you add the module below to the bottom of connection.js: exports.con = con This will make it so that the const 'con' can be used in any file that imports it, which will be necessary for the next step. 5- Manipulating the table Now that we've created the table, we wan't to manipulate it according to our needs. You can do this on the same file, but we'll create another one. On the server-files folder, create a file named database.js (or whatever you want). Once again, make sure to add the require module to index.js: require('./database.js') Now, back to database.js, add the following: const con = require('./connection').con; This will import the 'con' const from connection.js, so that we can use it on this file. Now, we want to add a player's Rockstar Games Social Services ID to our table once he joins for the first time. To do it, write the code above: mp.events.add('playerJoin', (player) => { const socialID = player.rgscId; console.log(`[SERVER]: ${player.name} [SCID: ${player.rgscId}, ID: ${player.id}] entrou no servidor.`); con.query('INSERT INTO players (scID, posX, posY, posZ) VALUES ('+socialID+', 174, -919, 30.687)', function (err, result) { if (err) { console.log('The following error happened while inserting a new record to [players]: ' + err) throw err; } else { console.log(`New player: ${player.name}`); }; player.spawn(new mp.Vector3(174, -919, 30.687)); }); }); With this code, once a player join's we'll get is Social ID, send a log to the console informing us about his connection, insert his Social ID into our database (so that we can identify him later) and spawning him on X: 174, Y: -919, Z: 30.687. Now, as we made it so that the scID (Social ID) was UNIQUE, if a player is already in the database we can't add him again, and if we try to it will return an error. So, if you connect to your server for the first time, you'll get the log: "New player: [Your Name]". If you connect again, you'll get the log: 'The following error happened while inserting a new record to [players]: Error: ER_DUP_ENTRY: Duplicate entry '12345678' for key 'players.scID'. This means it detected that the scID you tried to insert already existed and, because the column is unique, we can't insert a similar one. Now, we can use this error to our advantage, as we don't need to check if a value already exists, because the error already tells us if it does or not. So, replace the code above with the one below: mp.events.add('playerJoin', (player) => { const socialID = player.rgscId; console.log(`[SERVER]: ${player.name} [SCID: ${player.rgscId}, ID: ${player.id}] entrou no servidor.`); con.query('INSERT INTO players (scID, posX, posY, posZ) VALUES ('+socialID+', 174, -919, 30.687)', function (err, result) { if (err) { switch(err.code) { case "ER_DUP_ENTRY": console.log("The following error happened while inserting a new record to [players]: " + err); con.query('SELECT posX, posY, posZ FROM players WHERE scID = '+socialID+'', function (err, result) { if (err) { console.log('The following error happened while selecting scID from [players]: ' + err); throw err; } else { player.spawn(new mp.Vector3(result[0].posX, result[0].posY, result[0].posZ)); } }); break; default: console.log('The following error happened while inserting a new record to [players]: ' + err) throw err; } } else { console.log(`Novo jogador: ${player.name}`); }; player.spawn(new mp.Vector3(174, -919, 30.687)); }); }); With this code, if there's an rror we'll check if the error is "ER_DUP_ENTRY" (if the value is duplicated). If it is, we will stop trying to insert it and actually use the coordinates assigned to a Social ID to spawn the player with that Social ID on those coordinates. We select 'posX', 'posY' and 'posZ' from the row where the 'scID' value is equal to the Social ID of the player that joined the server and spawn that player in those positions. If there's an error while selecting the values, we'll make sure that it is logged. Also, as we don't know for sure that the only error that we will face is "ER_DUP_ENTRY", we make sure to add a switch statement. If the error is the mention, we'll try to spawn the player and if it isn't we'll log it. Now, we made it so that a player spawns in the coordinates associated to him, but we need to actually made those coordinates change whenever he leaves. For this, add this code to the same file: mp.events.add('playerQuit', (player, exitType, reason) => { const socialID = player.rgscId; pos = player.position console.log(`[SERVER]: ${player.name} [SCID: ${player.rgscId}, ID: ${player.id}] left the server.`); con.query('UPDATE players SET posX = '+pos.x+', posY = '+pos.y+', posZ = '+pos.z+' WHERE scID = '+socialID+'', function (err, result) { if (err) { console.log(err); throw err; } else { console.log("Coordinates added") } }); }); This code means that once a player quits the server, we'll log the console of his disconnect and update the 'players' table with the coordinates where he left the server. We search for the row where his Social ID equals 'scID' and change his coordinates to the ones we obtained with the 'pos' var. If we do it successfuly, we'll log to the console: "Coordinates added". If there's an error, we'll log it. This is it. Thank you very much. If you know of anyway I can make my code better, let me know.
-
Hello everyone! Many of you have decided to use Entity Framework instead of raw SQL but failed somehow in the process (myself included)! This is why I am creating this quick guide with some examples on how to use Entity Framework Core with MySQL database in RAGEMP C# gamemode. It's not perfect, but it will work just fine. If you find a mistake or have a better way of doing something, please let me know! Let's start! Requirements: - Visual Studio 17 or better - Net Core 2.2 - RageMP C# 0.3.7 - MySQL database (I use XAMPP) 1. First, you will need some dependencies. Open up the nuget package manager and add these dependencies to your project: Microsoft.EntityFrameworkCore - Version 2.2.0 Microsoft.EntityFrameworkCore.Tools - Version 2.2.0 Pomelo.EntityFrameworkCore.MySql - Version 2.1.4 Pomelo.EntityFrameworkCore.MySql.Design - Version 1.1.2 Pomelo.EntityFrameworkCore.MySql is a MySQL provider. There are many more providers, but Pomelo's is just fine. How it looks when everything's added: NOTE: As of writing this, you have to use exactly those versions I had screenshot above! 2. Now we are ready to create a DbContext class. I will just copy and paste and explain needed with comments! using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; namespace EFCoreTutorial { public class DefaultDbContext : DbContext { // Connection string, more details below private const string connectionString = "Server=localhost;Database=efcoretutorial;Uid=root;Pwd="; // Initialize a new MySQL connection with the given connection parameters protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql(connectionString); } // Account model class created somewhere else public DbSet<Account> Accounts { get; set; } } } Server = the address of the server, in this case localhost Database = name of the database Uid = user accessing the database Pwd = database password, leave empty if none 3. Create a model class, in this case it's called Account using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace EFCoreTutorial { public class Account { [Key] public int Id { get; set; } public string Username { get; set; } public string Password { get; set; } } } 4. Let's make a simple registration command. using System; using System.Collections.Generic; using System.Linq; using System.Text; using GTANetworkAPI; namespace EFCoreTutorial { public class Commands : Script { [Command("register")] public void AccountCmdRegister(Client player, string username, string password) { RegisterAccount(player, username, password); NAPI.Chat.SendChatMessageToPlayer(player, "~g~Registration successful!"); } public static void RegisterAccount(Client client, string username, string password) { // create a new Account object var account = new Account { Username = username, Password = password }; // When created like this, the context will be immediately deleted AKA disposed. // This will make sure you don't have slowdowns with database calls if one day your server becomes popular using (var dbContext = new DefaultDbContext()) { // Add this account data to the current context dbContext.Accounts.Add(account); // And finally insert the data into the database dbContext.SaveChanges(); } } } } 4a. To check if you are properly connected to the database without going into the game, make a query when a resource starts, for example: using System; using System.Collections.Generic; using System.Linq; using System.Text; using GTANetworkAPI; namespace EFCoreTutorial { public class Main : Script { [ServerEvent(Event.ResourceStart)] public void OnResourceStart() { using (var dbContext = new DefaultDbContext()) { var playerCount = dbContext.Accounts.Count(); NAPI.Util.ConsoleOutput("Total players in the database: " + playerCount); } } } } 5. Before we can test the command or the above example, we need to make a migration. Manual migrations are the only way as of EF Core. To use them in our gamemodes which are most often only libraries (.dlls), we need to "trick the system" into thinking our gamemode is executable. The easiest way is to "create" a console application. First, open your project properties, ALT + F7. Change output type to "Console Application" Save with CTRL + S! Create a new class called Program.cs with the code below: using System; using System.Collections.Generic; using System.Text; namespace EFCoreTutorial { public class Program { public static void Main(string[] args) { } } } Yes, that's right. You only need the Main method. It's because the console app approach looks for "Main" as a starting point. Save and build the project! Now let's make the first migration. Open up the Package Manager Console and type "add-migration FirstMigration" (FirstMigration is only the name). After the migration class has been created, type once again into the console "update-database". The very first migration is now added and inside your database you will find Accounts table: Note: If there are any errors by this stage, then you are most likely not connected to your Database. This guide will not cover that! 6. We are almost done. For server to properly work, it will need runtime dlls. When you first start RAGEMP client, you will download some runtime files. Those are not enough and you have to take some extra steps. Go to the "RAGEMP" root folder, then "dotnet" folder and copy everything. Paste it inside the "runtime" folder (RAGEMP\server-files\bridge\runtime). When you build your project, it will also give you runtime files. Copy everything from bin/debug/netcoreapp2.2 (default build path) except Bootstrapper.dll , Newtonsoft.Json.dll and everything that starts with YourProjectName (EFCoreTutorial in my case). Paste it once again inside the "runtime" folder (RAGEMP\server-files\bridge\runtime). Finally, open YourProjectName.csproj with notepad and add this line <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> like so: Save and close. 7. You are all set up! From now on you don't have to worry about missing runtimes, errors and whatnot. This is everything Entity Framework Core requires to work properly in RAGEMP. Changelog: - Added appsettings.json, a better way of handling connection strings. Thanks @horseyhorsey! - Some clarification - Cleaned and updated the code per @Adam's suggestion This was my first tutorial/guide. Leave feedback and opinions. Thank you for reading! xForcer
- 37 replies
-
- 11
-
- csharp
- entityframework
-
(and 2 more)
Tagged with:
-
Version 0.0.2
772 downloads
This resource will help many newcomers in the development of the server. At this gamemode, used the sequelize framework, for easy work with the database. Also used frameworks ReactJS + ReduxJS special for CEF. GitHub URL: https://github.com/HEXisGOD/RAGEMP_sequelize_react_redux Installing 1. Download this archive, unpack it in RAGE:MP new server folder. 2. To work with the database locally I suggest using Denwer. 3. Config connection data at packages\sequelize\modules\db.js 4. Import example database into phpMyAdmin 5. Then start server, and test it !) Needed node modules 1. MySQL2 - [ npm install mysql2 -save ] 2. Sequelize - [ npm install sequelize -save ] - Thanks @kemperrr for make "pleaseCallCEF" function and event on ReactJS!! This is first version, During the time there can be changes and improvements!! -
Version 1.2
4676 downloads
UPDATE I highly recommending using my more updated resource "MySQL Accounts" instead as it fixes known issues and runs better: This resource will stay up, however I will not be giving any help for this resource as I don't believe it should be used for serious projects. ---- Basic MySQL Gamemode Github Link: https://github.com/MrPancakers/ragemp-mysql Resource Thread: Discord: MrPancakers#9283 This is a template of a very basic login/registration system you can implement into your game mode to get started. This template only stores usernames, passwords(encrypted with BCrypt), position and money so anything extra will need to be implemented yourself. This is intended for beginners so the code is pretty basic and nothing fancy has been done so it is easily readable. If you find any issues, leave a comment on my thread or leave a comment on this resource. Installation You'll need to have a MySQL server setup, either using WAMP/XAMPP/or from a server. To keep this short I will not go through setting these up, simply Google 'How to set up WAMP' for example to get it set up. Unzip the source and place it inside of your server files folder. Open your command prompt and change your directory to your server folder. Then do 'npm install' to install the required node_modules. Create a new database and call it whatever you want (Inside the script it is called 'ragemp-mysql'). Once created, import the ragemp-mysql.sql into your newly created database. Go to packages/mysql/mysql.js and open it. At the top is the connection info, change this to whatever your IP and MySQL username/password is. If you're hosting this locally and you haven't made/changed the MySQL info, the default should be fine. You're all set to go.- 22 comments
- 9 reviews
-
- 10
-
Version 2.1
475 downloads
User Control System for all Roleplay Projects! Have fun! GitHub: https://github.com/eodclan/User-Control-System Please note: The upload avatar folder needs write access! Version: 2.5 Changelog: Added: New Site Settings Feature Added: Download Section Changed: Themes from UCP ( Left Navigation ) Changed: Login System Changed: Session System for the Site Settings Feature And a lot of minor changes. Main requirements: 1. MySQL Server 2. Webserver 3. Php 8.x or newer Features requirements: 1. Login & Register System 2. Staff Tools ( User Changer, Playerlist, News Creator, Rules Creator ) 3. Language System ( English & German ) 4. Support System 5. Profile Changer 6. Twitter System 7. and more Have fun DerStr1k3r -
Moin, Ich kriege diesen Fehler: mysql:134 Error: could not locate file lib/Connection.js Class = require('./lib/Connection'); Jemand eine Idee woran das liegt?
-
- mysql error
- mysql
-
(and 1 more)
Tagged with:
-
Hi, i am new to C# and rage development, i was trying to follow MySQL tutorial by Outwardly Experience but after starting server i get these warnings: Could not load file or assembly 'System.Security.Permissions, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified. Could not load file or assembly 'System.Drawing.Common, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified. Could not load file or assembly 'System.Drawing.Common, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified. Could not load file or assembly 'System.Drawing.Common, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified. Exception thrown: 'System.IO.FileNotFoundException' in MySql.Data.dll Exception thrown: 'System.IO.FileNotFoundException' in System.Private.CoreLib.dll An exception of type 'System.IO.FileNotFoundException' occurred in System.Private.CoreLib.dll but was not handled in user code Could not load file or assembly 'System.Drawing.Common, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified. I tried installing System.Security.Permissions in NuGet manager but that did not work, i also tried copying .dlls to runtime folder, still same errors. My dependencies: Any help would be great Tutorial link: https://www.youtube.com/watch?v=1QBj-DO6APM
-
Hello. I'm trying to connect to mysql database and execute a query but it doesn't work. It doesn't even print "Test" in the console. Here's the code: database.js var mysql = require('mysql'); var mysqlConfig = mp.config.mysql; var mysqlc = mysql.createConnection({ host: mysqlConfig.host, user: mysqlConfig.user, password: mysqlConfig.password, database: mysqlConfig.database }); module.exports.createAccount = function(name) { try { console.log(1); var query = "INSERT INTO `accounts` (`name`, `money`) VALUES ?"; var values = [name, 0]; console.log("Connecting to database.."); mysqlc.connect(function(err) { console.log("Test"); if (err) { console.log("MYSQL ERROR: " + err); } else { console.log("Database connection successful!"); mysqlc.query(query, values, (err, result) => { if (err) throw err; console.log(result); }); } }); } catch (err) { console.log(err); }; }; events.js var db = require('./database'); mp.events.add('playerJoin', (player) => { db.createAccount(player.name); }); This is my console output: [N] Starting network... - OK: (IPv4-only) at 127.0.0.1:22005 (node:13956) ExperimentalWarning: The ESM module loader is experimental. Loading packages "test" loaded [P] Plugin bridge.dll loaded! Started HTTP server at 22006 port. 1 Connecting to database..
-
Hello! I tried to connect to the DB, but the server threw an error. CS0012: The type 'DbConnection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. -> MySQL/MySQL.cs:37 When i add a reference I get it: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Option not supported. Parameter name: db at MySql.Data.MySqlClient.MySqlBaseConnectionStringBuilder.GetOption(String key) at MySql.Data.MySqlClient.MySqlConnectionStringBuilder.set_Item(String keyword, Object value) at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value) at MySql.Data.MySqlClient.MySqlBaseConnectionStringBuilder..ctor(String connStr, Boolean isXProtocol) at MySql.Data.MySqlClient.MySqlConnection.set_ConnectionString(String value) at MySQL.MySQL.StartConnection() in MySQL/MySQL.cs:line 35 at VesRP.Setts() in VesRP.cs:line 11 --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at GTANetworkInternals.ScriptingEngine.InvokeVoidMethod(String method, Object[] args) at System.Collections.Generic.List`1.ForEach(Action`1 action) at GTANetworkInternals.EventHandler.ParseEx(Event _event, ScriptingEngine engine, Object[] arguments) at System.Collections.Generic.List`1.ForEach(Action`1 action) at GTANetworkInternals.GameServer.StartResource(String resourceName, String parent) MySQL connection code: String SQLConnection = $"SERVER={sql.Host};PASSWORD={sql.Pass};UID={sql.User};DATABASE={sql.DB};"; conn = new MySqlConnection(SQLConnection); try { conn.Open(); NAPI.Util.ConsoleOutput("Connected!"); } catch(Exception ex) { NAPI.Util.ConsoleOutput("Error:"+ex.ToString()); }
-
I installed the Muscle library from NuGet manager How to fix this error? thanks string connStr = "server=localhost;user=admin;database=rage;password=1;"; string sql = "INSERT INTO base (a,b,c,d,e)" + "VALUES(2, 'логин', 321, пароль', 9999)"; MySqlConnection con = new MySqlConnection(connStr); MySqlCommand cmd = new MySqlCommand(sql, con); con.Open(); cmd.ExecuteNonQuery(); And I have second question, why fix this? Message from console: WARNING: "SetPlayerNametagVisible" function is not implemented yet. DEPRECATE: SetPlayerNametag is deprecated. Thank you in advance.
-
Just so title say, what you guys thinks is better for some simple gamemode. MySQL or .JSON type of storing data. I tried to use one and another. Must say that MySQL is more safer for storing data and more organized (my opinion). But I chose .JSON because it's much easier to get use to work with it, and much simpler for coding then mySQL. What do you guys think?
-
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Data.Common, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Не удается найти указанный файл. at new ServerSide.mysqli(string host, string user, string password, string db) at new ServerSide.Manager() in D:\rumod\ragemp\server-files\ragemp_csharp_scripts\ragemp_uncomiled_scripts_csharp\ServerSide\Manager.cs:line 9 --- End of inner exception stack trace --- at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at GTANetworkInternals.GameServer.<InstantiateScripts>d__61.MoveNext() at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext() at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable) at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) at GTANetworkInternals.GameServer.StartResource(String resourceName, String parent) Я подключил модуль MySql, написал реализации класса, но появляются такие ошибки. Сразу скажу, что он не может найти библиотеку я понимаю, дело в том, что она присутствует. I connected the MySql module, wrote class implementations, but such errors appear. I must say right away that he cannot find the library, I understand, the fact is that it is present.
-
This tutorial will only work if you already have your MySQL + RAGE project set up. Step 1 Right-click on your project and select 'Manage NuGet Packages...'. Browse for the following packages and make sure you install the same version for all! (this example uses version 2.2.0) Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Tools Pomelo.EntityFrameworkCore.MySql Step 2 Create a Player.cs class with the following code: Step 3 Create a new class called '<myProject>Context.cs', in this example we will use TutorialContext.cs Paste the following code: Step 4 To make things easier for future classes, we will make an interface called IRepository.cs. This is not part of EF Core but it's a nice programming pattern to use with it. Copy-paste the code below into your interface: Step 5 Create a class called PlayerRepository.cs Now we will implement the interface we just created in our PlayerRepository.cs Step 6 Create a class called Main.cs so we can test our code on ResourceStart event. Paste the following code Step 7 Build and run your server You may get an error like: This means that in your RAGE runtime folder (D:\RAGEMP\server-files\bridge\runtime) you are missing the necessary dlls. Head over to (for example) A:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.entityframeworkcore\2.2.0\lib\netstandard2.0 and copy the needed .dll to the runtime folder of RAGE. You might have to do this for a couple of dlls. Just go back to the NuGetFallbackFolder and find the right one. If you fixed these errors, this should be the result: Step 8 (Extra) If you're adding more and more classes and you want to add changes to your database, use the following method: Create your new class (House.cs for example) and go back to your TutorialContext.cs and add public DbSet<House> Houses { get; set; } under Players (which we did in this tutorial). On the top left of your Visual Studio you will see a tab called 'View'. Click on it, go to 'Other Windows' and select 'Package Manager Console'. In the Package Manager Console, type: Add-Migration addedHouse Wait for the console to finish and type: Update-Database Your house class has now been added to the database. Enjoy.
- 2 replies
-
- 3
-
- Entity Framework Core
- MySQL
-
(and 2 more)
Tagged with:
-
(username is player.name normally just changed it to test something, with player.name its the same error. so username = player.name) Server Side Code: https://imgur.com/a/mgQMsdi Console Error Message: https://imgur.com/a/cmt2Tg8 Help would be awesome, thanks in advantage.
-
Hey, ich bin ziemlich neu im C# Programmieren, belege derzeitig noch einen Video Kurs auf udemy.com und programmiere nebenbei kleinweise eine RP Resource. Ich stehe nun kurz davor das ganze mit einer Datenbank zu verbinden. Nun wollte ich fragen, ob es egal ist das ganze einfach nur via Mysql mit der Datenbank zu verbinden oder gibt es noch bessere Wege. Nebenbei wollte ich fragen, ob eine Verbindung mit der Datenbank alleine via C# möglich wäre und ob's empfehlenswert ist. Liebe Grüße, Jeff
-
Hey is it possible to spawn vehicles with tuning modification. And how to save Tuning modifications in mysql and load them when a player join the server.
-
Hi guys! Am about to start programming my new server, but I cannot use MySQL. I started with this tutorial -> https://rage.mp/forums/topic/1807-c-getting-started-debugging/ This is how my code looks like: using System; using System.Data; using GTANetworkAPI; using MySql.Data.MySqlClient; namespace GTV { class MySQL { private string connectionString = "SERVER=localhost;" + "DATABASE=gtv;" + "UID=root;" + "PASSWORD=;" + "SslMode=none"; public bool FirstConnect() { MySqlConnection db = new MySqlConnection(connectionString); db.Open(); string state = db.State.ToString(); NAPI.Util.ConsoleOutput(state); if (db.State == ConnectionState.Open) return true; else return false; } } } And here my pretty long exception: What did I do wrong? Thank you for your help.
-
При использование базы данных, сервер через пару минут после запуска выдаёт исключения: ==================[14.07.2018 4:32:29]================== System.Net.Sockets.SocketException (0x80004005): Программа на вашем хост-компьютере разорвала установленное подключение at void System.Net.Sockets.NetworkStream.Write(byte[] buffer, int offset, int size) ========================================================= ==================[14.07.2018 4:32:29]================== System.IO.IOException: Unable to write data to the transport connection: Программа на вашем хост-компьютере разорвала установленное подключение. ---> System.Net.Sockets.SocketException: Программа на вашем хост-компьютере разорвала установленное подключение at void System.Net.Sockets.NetworkStream.Write(byte[] buffer, int offset, int size) --- End of inner exception stack trace --- at void System.Net.Sockets.NetworkStream.Write(byte[] buffer, int offset, int size) ========================================================= ==================[14.07.2018 4:32:29]================== System.IO.IOException: Unable to write data to the transport connection: Программа на вашем хост-компьютере разорвала установленное подключение. ---> System.Net.Sockets.SocketException: Программа на вашем хост-компьютере разорвала установленное подключение at void System.Net.Sockets.NetworkStream.Write(byte[] buffer, int offset, int size) --- End of inner exception stack trace --- at void System.Net.Sockets.NetworkStream.Write(byte[] buffer, int offset, int size) at void MySql.Data.MySqlClient.TimedStream.Write(byte[] buffer, int offset, int count) ========================================================= Метод подключения к базе данных: private const string connectionString = "Server=localhost;Database=db;port=3306;User Id=root;password=;SslMode=none"; public static void TestConnection() { MySqlConnection conn = new MySqlConnection(connectionString); try { NAPI.Util.ConsoleOutput("[Database] Connection to MySQL ..."); conn.Open(); } catch (Exception ex) { NAPI.Util.ConsoleOutput("[Database] " + ex.ToString()); } conn.Close(); NAPI.Util.ConsoleOutput("[Database] Done"); } Порты 22005 и 22006 открыты, отключение файервола изменений не принесло
-
Добрый день. Я начинающий скриптер. Как реализовать авторизацию и Регистрацию в игре через MYSQL? прошу дать пошаговую инструкцию. Благодарю.