Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect swift to sql server

Tags:

Swift 3 / Xcode 8.3.3

I have an SQL server running on phpmyadmin and I would like to send an SQL request (like : SELECT * FROM database) directly from my Swift code. I did a lot of research but all of the answer use PHP.

In the end, I would like to transform this Java code into Swift:

try (Connection connection = DriverManager.getConnection(url, username, password)) {
    System.out.println("Database connected!");

    // the mysql insert statement
    String query = "SELECT * FROM dbName";

    Statement st = connection.createStatement();
    st.executeUpdate(query);

} catch (SQLException e) {
    throw new IllegalStateException("Cannot connect the database!", e);
}
like image 264
bastosCoder Avatar asked Sep 06 '17 14:09

bastosCoder


People also ask

Can you use SQL with Swift?

SQLite is a C API that will have you work with both SQL, and... C from Swift. There exist Swift libraries that wrap the C functions in Swift, so that you don't have to learn C from Swift: GRDB - this is my favourite since I created it - but many other people love it as well.

Can I use Xcode for SQL?

You can use the C-Interface routines to pass SQL commands to a Database with X-Code - all of the Database programs have C and Java libraries for that purpose.

Which database is best for iOS Swift?

Some may argue that Core Data's ties with Apple make it the most acceptable iOS database for Apple-specific languages such as Swift and Objective-C. Other capabilities, however, give Core Data the upper hand as the database for your iOS app. Core Data fetches data faster than SQLite database.


2 Answers

First you must write a web service (PHP, JAVA) to query your database.

Create a php code to handle your ios query

    <?php

// Create connection
$con=mysqli_connect("localhost","username","password","dbname");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}



// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Locations";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

// Close connections
mysqli_close($con);
?>

Next, you need to host your php code to a webhost 'use www.000webhost.com for example'

Then, get the php code from the webhost 'www.000webhost.com/db.php'

Now in your swift code connect to the database via the link you just created

    @IBAction func sendQuery(_ sender: Any) {


        let url = URL(string: "https://wanagetout1.000webhostapp.com/db_copy.php")!

        var request = URLRequest(url: url)

        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        let postString = "your query"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                // check for fundamental networking error
                print(error!)
                return
            }
}
like image 188
Achraf Avatar answered Oct 14 '22 21:10

Achraf


Though you can use REST API to fetch data from any server, but if your project has the requirement to connect with sql server directly from your swift project then you can use "SQLClient" to connect. You will get solution from here - https://github.com/salmasumona/Call-SP-from-iOS-project-using-SQLClient

like image 30
Sumona Salma Avatar answered Oct 14 '22 20:10

Sumona Salma