I used node js to connect mysql server and it is working good. I used the API developed in node js and used in the local macOS app. The problem is querying the data from mysql database on workbench is fast but in node js API it is very delay. So, I've to connect mysql db directly from my macOS app.
I installed mysql from here: https://www.mysql.com/downloads/
Also I am using mysql work bench to test the connection and It is connecting without any problem. So, In system preference I've an mysql extensions to start and stop mysql server. In the extension I can see the root folder locate in /usr/local/mysql
I created new project and added swift package of mysql-nio from here
In that repository their API document link is broken https://api.vapor.codes/mysql-nio/master/MySQLNIO/ But I found the correct link https://api.vapor.codes/mysql-nio/main/MySQLNIO/MySQLConnection/
By using that link, I tried to connect with below code,
//https://github.com/vapor/mysql-nio
import Cocoa
import MySQLNIO
class ViewController: NSViewController {
private var group: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 4)
private var eventLoop: EventLoop {
return self.group.next()
}
override func viewDidLoad() {
super.viewDidLoad()
do{
let socketAddress = try SocketAddress(ipAddress: "127.0.0.1", port: 3306)
let logger = Logger(label: "MyLogger")
let connection = MySQLConnection.connect(to: socketAddress, username: "root", database: "MyDB", password: "3$#sdRt34#sdf$dja2", tlsConfiguration: nil, serverHostname: nil, logger: logger, on: eventLoop)
connection.whenComplete { result in
switch result{
case .success(let connection):
print("Success! Status closed: \(connection.isClosed)")
case .failure(let error):
DispatchQueue.main.async {
NSApp.presentError(error)
}
}
}
}catch{
NSApp.presentError(error)
}
}
}
Error:
The operation couldn’t be completed. (NIOCore.IOError error 1.)
I added App Transport Security Settings -> Allow Arbitrary Loads to YES in the xcode project info
I don't know How to resolve this issue. Can you please help me to resolve this issue? Thank you!
In the app sandbox, you'll need to enable "Outgoing connections (client)" and then it should work.
Unfortunately, because of a Swift bug the error printout of Swift errors isn't actually useful if you do localizedDescription. To see the actual error, you'd need to put something like a print(error) in your error handler.
See how in the screenshot below, the print(error) prints actually useful text like connect(descriptor:addr:size:): Operation not permitted (errno: 1) if I don't check the "Outgoing connections (client)"?
Related
Future<List> senddata() async {
} final response = await http.post(Uri.parse(("``http://localhost/app/insertdata.php``"), body: {
) "name": user.text
"email": pass.text
"mobile":mobile.text
});
var datauser = json.decode(response.body);
connection file to a database, have but does not display any errors
Make sure your device is connected to internet
You need to establish connection to the SQL first before requesting any thing in your localhost
Your application and localhost server should be running on the same port to use API's locally in your application.
I am trying to use SSL in my MySQL Connection String but it is giving me this error
Error: UrlError { Unknown URL parameter 'ssl-mode' }
I have referred to official documents from this link: https://dev.mysql.com/doc/refman/8.0/en/connecting-using-uri-or-key-value-pairs.html.
My connection string looks as follows :
----------------------------------------------------------------------------------------------------------
let connection_string = format!("mysql://{}:{}#{}?ssl-mode=REQUIRED", &user_name, &password, &hostname);
----------------------------------------------------------------------------------------------------------
let connection_url: &str = &connection_string;
let pool = Pool::new(connection_url)?;
let mut connection = pool.get_conn()?;
I am still a rookie in using rust. So please let me know if I am doing something wrong here.
Also if possible please suggest me a better way of approaching.
Thank you !!
In order to encrypt your connection to MySQL with TLS/SSL, you need to create an SslOpts instance and pass that to the OptsBuilder instance via its ssl_opts() method.
Here is an example how to create an SslOpts instance via with_danger_accept_invalid_certs():
let builder = OptsBuilder::new();
let opts = builder
.ip_or_hostname(Some("..."))
.db_name(Some("..."))
.user(Some("..."))
.pass(Some("..."))
.ssl_opts(SslOpts::with_danger_accept_invalid_certs(SslOpts::default(), true));
let db_pool = Pool::new_manual(2, 10, opts);
Using with_danger_accept_invalid_certs() is simple, although, as the name suggests, it might not be the most secure option. It should be much more secure than no encryption at all. Depending on your needs, you might want to take a look at the other options provided by the crate.
I'm trying to create an application that fetches data from the MySQL server.
I installed MySQL from Homebrew and using the PerfectMySql swift package.
I want to test it on my localhost first but I'm unable to connect it from my application.
When I mysql -u root -p in the command line, it works as it should.
My code for MySQL connection:
import PerfectHTTP
import PerfectHTTPServer
import PerfectMySQL
import Foundation
public class DB {
let host = "localhost" // or "127.0.0.1"
let user = "root"
let password = "12345678"
let database = "pets"
func databaseConnect(host: String, user: String, password: String, db: String) -> MySQL {
let mysql = MySQL() // Create an instance of MySQL to work with
let connected = mysql.connect(host: host, user: user, password: password, db: db)
guard connected else {
// verify that we have connected successfully
print(mysql.errorMessage())
return mysql
}
return mysql
}
public func insertGame(title: String, description: String, createdDate: String){
// Connect to our database
var db = databaseConnect(host: host, user: user, password: password, db: database)
defer {
db.close() //This defer block makes sure we terminate the connection once finished, regardless of the result
}
// Create the statement we wish to execute
let statement = MySQLStmt(db)
let insert = "INSERT INTO game(id, title, description, release_date) VALUES (\(statement.insertId()), '\(title)', '\(description)', '\(createdDate)');"
_ = statement.prepare(statement: insert)
// Run the query
let querySuccess = statement.execute()
// Check that our query was successfuly, otherwise return out
guard querySuccess else {
print(db.errorMessage())
return
}
print("Insert successful!");
}
}
When I start my application in Xcode, it gives me this error:
host = "127.0.0.1"
host = "localhost"
I searched the web and StackOverflow for hours but couldn't find anything to fix this issue.
Every other question asked here or other forums are about fixing connection problems via Terminal, which is not the issue for me here.
Only a related question asked here but it is unfortunately unanswered. -> Can't connect to MySQL server on 'localhost'
You said that you were receiving the following error on your macOS client.
Can't connect to MySQL server on '127.0.0.1' (1)
I know you've probably figured it out by now, but for the sake of future readers, this message (which returns an error code of 2003) can result on macOS targets if you neglect to enable “Outgoing Connections (Client)”:
I ran into this exception while I was working with Angular to show my Flask API REST data which is deployed on an nginx server:
{ "error": "(_mysql_exceptions.ProgrammingError) (2014, \"Commands out of sync; you can't run this command now\") [SQL: 'SELECT ......" }
This exception is caused by this function that sends two requests at the same time to the database:
ngOnInit() {
let url = this.baseUrl + `/items/${this.id}`;
this.httpClient.get(url).subscribe((data : Array<any>)=> {
this.ItemToEdit = data;
});
let url = this.baseUrl + '/products'
this.httpClient.get(url);
}
I use SQLAlchemy in the API with Mysql database. I thought that If I add a pool connection it will be resolved but It didn't, I still get same exception:
engine = create_engine(connection_string, pool_size=20, max_overflow=0)
What exactly should I do to handle this ?
Is there anything else to set on the server side to make this function work without getting an exception ?
EDIT:
Is this an observable handling problem or it can be fixeb by using Gunicorn with nginx on server side ?
Using Gunicorn solved my problem.
I launch the application this way:
gunicorn -b 0.0.0.0:5000 --workers=5 myapi:app
And I don't see the error anymore even with 3 mysql requests in ngOnInit
I am retrieving data from URL like this:
let url = NSURL(string: baseURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = JSON(data: data!)
let results = swiftyJSON[0]["name"]
print(results)
} else {
print("error")
}
}
For the above, I get data like this:
[
{
"_id":"123",
"_rev":"345",
"name":"hey"
},
{
"_id":"133",
"_rev":"33345",
"name":"hello"
}
]
I always end up in error block and I am not sure why?
I pasted the JSON in chrome console and able to do swiftyJSON[0].name. I would like to print all elements from the above json OBJECT.
Error:
error Optional(Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={NSUnderlyingError=0x7f87514ab570 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorCodeKey=8, _kCFStreamErrorDomainKey=12}}, NSErrorFailingURLStringKey=http://localhost:3000/idea, NSErrorFailingURLKey=http://localhost:3000/idea, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=A server with the specified hostname could not be found.})
Please note, localhost:3000 is on.
The error you pasted may be the request's hostname not found.
"A server with the specified hostname could not be found." The JSON parse seems right totally.
The error is not in the JSON data. The data cannot be retrieved in the first place since the URL http://localhost:3000/idea is not working.
Most likey, the URL is valid on your Mac but not on your iPhone. The URL would only be valid if your server side was running on the iPhone or simulator itself, which is rather unlikely.
localhost isn't a global address. On your Mac, it refers to your Mac. On an iPhone, it refers to the iPhone itself.
Open the Network Utility app on your Mac, look up the IP address and replace localhost with your IP address, e.g. http://192.168.1.37:3000/idea. Then your iOS app will be able to retrieve the data.