投稿時間:2022-04-16 07:17:25 RSSフィード2022-04-16 07:00 分まとめ(22件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
Google カグア!Google Analytics 活用塾:事例や使い方 アプデしたstand.fmでフォローされるためにした5つの方法 https://www.kagua.biz/marke/podcast/20220416a1.html standfm 2022-04-15 21:00:51
python Pythonタグが付けられた新着投稿 - Qiita SNSからWeb漫画ランキングを自動生成したら、話題の漫画が集まった【個人開発】 https://qiita.com/bonzeboy/items/35f151d818305b1fdc58 httpbookle 2022-04-16 06:33:09
python Pythonタグが付けられた新着投稿 - Qiita Pytorchモデルの保存、読み込み https://qiita.com/john-rocky/items/2d95c68a6f34a760275d argskwargsmodelloadstat 2022-04-16 06:01:38
js JavaScriptタグが付けられた新着投稿 - Qiita 2011年のJavaScript本は古い - 2022年、freeCodeCamp日本語版の紹介 https://qiita.com/e99h2121/items/f941c8c9e055a328f74c amazon 2022-04-16 06:44:10
AWS AWSタグが付けられた新着投稿 - Qiita SNSからWeb漫画ランキングを自動生成したら、話題の漫画が集まった【個人開発】 https://qiita.com/bonzeboy/items/35f151d818305b1fdc58 httpbookle 2022-04-16 06:33:09
海外TECH Ars Technica Before Google kills free Gsuite accounts, why not offer a family email plan? https://arstechnica.com/?p=1848041 doesn 2022-04-15 21:06:16
海外TECH MakeUseOf These 5 Opera Add-Ons Will Enhance Your YouTube Experience https://www.makeuseof.com/opera-add-ons-enhance-youtube/ browser 2022-04-15 21:30:13
海外TECH DEV Community Building an application with Go and SQLite https://dev.to/pluralsight/building-an-application-with-go-and-sqlite-11h Building an application with Go and SQLiteToday we re going to learn how to use SQLite with Go By the time you finish this tutorial you can build CRUD Create Read Update Delete applications with Go easily Go is one of the hottest languages in development right now known for its simple structure and blazing performance SQLite has been trending among developers for its ability to host small data very quickly safely and contained in a single file Why SQLite Great PerformanceTiny footprintSelf contained file based In fact you re likely already using SQLite every day and you don t know it It s ubiquitous in mobile phones and devices and SQLite powers many websites today So we re going to combine these two technologies to show you how easy it is to marry the two What this tutorial coversWe ll build a CLI command line interface application with Go and SQLite It will cover CreatingReadingUpdatingDeletingWith SQLite You can follow along and build this application or use this as a reference to build something of your own I ll start with pre populated database you can download here It has a database full of people with their first name last name email address and IP address We ll start by creating a menu then building out methods for each operation and in the end you ll have an application that looks like this So let s get started Creating the menu systemWe will build a CLI application that accesses a SQLite database I m going to use The WMenu package from Dixonwille for this so we have an interface for our data We ll use this menu and a scanner to accept input to interact with our database We won t focus too heavily on the menu system itself because the intent of this article is to show you how to utilize SQLite First we ll create a Go module and work with main go to start Install the WMenu package go get github com dixonwille wmenuLet s create a main go that looks like this package mainimport log github com dixonwille wmenu v func main menu wmenu NewMenu What would you like to do menu Action func opts wmenu Opt error handleFunc opts return nil menu Option Add a new Person true nil menu Option Find a Person false nil menu Option Update a Person s information false nil menu Option Delete a person by ID false nil menuerr menu Run if menuerr nil log Fatal menuerr We will create a menu with the following options Add a new PersonFind a PersonUpdate a Person s informationDelete a person by IDNotice we are calling a function named handleFunc opts to handle which option is chosen menu Action func opts wmenu Opt error handleFunc opts return nil So let s create that function and have it display some values for now func handleFunc opts wmenu Opt switch opts Value case fmt Println Adding a new Person case fmt Println Finding a Person case fmt Println Update a Person s information case fmt Println Deleting a person by ID case fmt Println Quitting application When we run the application you should see a menu that looks like this When you make a selection it should display what you selected This is the menu we will use to interact with our SQLite Go code I will break it up into CRUD parts and we ll add to it as we go along So let s dive in We ll start with a quick look at the database The SQLite databaseThe database we re using for this exercise is available here The Schema is pretty simple We are storing people with the following attributes The create statement is here CREATE TABLE people id INTEGER first name TEXT last name TEXT email TEXT ip address TEXT PRIMARY KEY id AUTOINCREMENT I ve populated it with fake data from Mockaroo my favorite test data generator We will access this data and add to it without our Go CLI application In the spirit of CRUD we ll build out our application in that order Create Read Update Delete Connecting to the databaseWe ll need to add some additional code to connect to the database We ll use an object to create a connection and we can pass it to other parts of the program First to catch errors in our code let s create a simple function named checkErr that looks like this func checkErr err error if err nil log Fatal err Next let s add the go sqlite library from mattn to connect with SQLite go get github com mattn go sqliteThis is by far the best SQLite library for Go that I ve used It s easy fast and well documented Then we ll create a connection to our database in the main func Connect to databasedb err sql Open sqlite names db checkErr err defer closedefer db Close What this does is create a db object The sql Open method opens up names db as a SQLite database It s a simple step Then we defer the close of the database Now let s refactor our menu code so we can pass this object into our menu actions Change this menu Action func opts wmenu Opt error handleFunc opts return nil to this menu Action func opts wmenu Opt error handleFunc db opts return nil And add the parameter to our functionfunc handleFunc opts wmenu Opt to this func handleFunc db sql DB opts wmenu Opt Now we can pass this database connection and use it with our options Creating a modelLet s create a model we can use to store and transport our person records We ll want to separate this into a new file I ve named it person go In that file I ll create a struct that matches the datatype of our record package mainimport github com mattn go sqlite type person struct id int first name string last name string email string ip address string Save the file Creating a new recordWe will add the functionality to create a new record in the database You can use DB Browser for SQLite to access this database to verify changes First we ll add some code to handle the data If you remember back in main go we have a switch statement within handleFunc that looks like this func handleFunc opts wmenu Opt switch opts Value case fmt Println Adding a new Person Let s change that to handle accepting a new record as input case reader bufio NewReader os Stdin fmt Print Enter a first name firstName reader ReadString n fmt Print Enter a last name lastName reader ReadString n fmt Print Enter an email address email reader ReadString n fmt Print Enter an IP address ipAddress reader ReadString n newPerson person first name firstName last name lastName email email ip address ipAddress addPerson db newPerson breakHere we use a bufio scanner to read in the first name last name email address and IP address of a new person We read those values into a buffer one by one then create a new person struct and pass that to the addPerson method which doesn t exist yet The menu system will prompt us for these values one by one and then save them to the database Open up person go and let s create the addPerson method func addPerson db sql DB newPerson person stmt db Prepare INSERT INTO people id first name last name email ip address VALUES stmt Exec nil newPerson first name newPerson last name newPerson email newPerson ip address defer stmt Close fmt Printf Added v v n newPerson first name newPerson last name This function takes the db object and the new person struct and inserts it into the database We create a new SQL statement stmt We use db Prepare to prepare our insert statement and protect the application from SQL injection Then we run stmt Exec with the parameters we want to insert Then defer the close method and print our results Save the file and let s run it You can see our menu come up ask us for each part of the record then save it We can check the database and confirm that it was saved Now you may notice something here Notice the line breaks right after the first name This is because the newline when you press enter is scanned into the buffer and it saves into the database this way But we can fix this problem easily We can trim the suffix of each of those strings like this firstName strings TrimSuffix firstName n To remove the newline before it s inserted into the database So refactor your case statement to look like this case reader bufio NewReader os Stdin fmt Print Enter a first name firstName reader ReadString n if firstName n firstName strings TrimSuffix firstName n fmt Print Enter a last name lastName reader ReadString n if lastName n lastName strings TrimSuffix lastName n fmt Print Enter an email address email reader ReadString n if email n email strings TrimSuffix email n fmt Print Enter an IP address ipAddress reader ReadString n if ipAddress n ipAddress strings TrimSuffix ipAddress n newPerson person first name firstName last name lastName email email ip address ipAddress addPerson db newPerson breakNow let s rerun it and add another person Now we can see that the newline was removed and it even looks proper in the database We ll go back and fix Lloyd at a later time Now we have our Create portion finished We can now create new people for this database Reading a recordNow we want to read a record the functionality in our second menu option menu Option Find a Person false nil We will create code to find a person by their name Add the following to the case statement in handleFunc changecase fmt Println Finding a Person Tocase reader bufio NewReader os Stdin fmt Print Enter a name to search for searchString reader ReadString n searchString strings TrimSuffix searchString n people searchForPerson db searchString fmt Printf Found v results n len people for ourPerson range people fmt Printf n nFirst Name s nLast Name s nEmail s nIP Address s n ourPerson first name ourPerson last name ourPerson email ourPerson ip address breakHere we create another bufio reader to read from standard input your keyboard We read in the name you search for into searchString Then we will create a variable named people to store our results in It s populated by the searchForPerson function that we ll create This function returns a list of people results based on our search string It could be one or more results so we ll print out how many people we find Then we ll loop through the results and display them on the screen In person go let s create a searchForPerson function func searchForPerson db sql DB searchString string person rows err db Query SELECT id first name last name email ip address FROM people WHERE first name like searchString OR last name like searchString defer rows Close err rows Err if err nil log Fatal err people make person for rows Next ourPerson person err rows Scan amp ourPerson id amp ourPerson first name amp ourPerson last name amp ourPerson email amp ourPerson ip address if err nil log Fatal err people append people ourPerson err rows Err if err nil log Fatal err return people We ll create this function that takes the db object and a search string and returns a slice of person objects structs We ll run a SELECT statement to select id first and last name email and IP address based on whether the first or last name matches our search string We iterate through each row create a person struct and populate it with the resulting data Then we append it to our slice and return the completed collection with the function Let s build it and run it Run the program and select to find a person and search for a first and last name and you ll see the results Great stuff Now let s build something to update these records Updating a recordNow we can add people and look them up What if we want to update the information If you remember we inserted Lloyd Christmas with newlines attached to it So let s build something to update the record and save it This one will be a little different Here s how it works Get an ID from user inputRetrieve a record from that ID and put it in a person struct Display the current value when asking for a new valueSave new value into a new structSave the update s to the database In main go let s add another case for our third menu option replace case fmt Println Update a Person s information with case reader bufio NewReader os Stdin fmt Print Enter an id to update updateid reader ReadString n currentPerson getPersonById db updateid fmt Printf First Name Currently s currentPerson first name firstName reader ReadString n if firstName n currentPerson first name strings TrimSuffix firstName n fmt Printf Last Name Currently s currentPerson last name lastName reader ReadString n if lastName n currentPerson last name strings TrimSuffix lastName n fmt Printf Email Currently s currentPerson email email reader ReadString n if email n currentPerson email strings TrimSuffix email n fmt Printf IP Address Currently s currentPerson ip address ipAddress reader ReadString n if ipAddress n currentPerson ip address strings TrimSuffix ipAddress n affected updatePerson db currentPerson if affected fmt Println One row affected breakWe create another bufio scanner to read in the ID you want to update Then we search for that id with getPersonById and store it in currentPerson Then we go through each value and display the current value while asking for a new value If the user presses enter it will keep the current value If they type in something new it will be updated in the currentPerson object Then we ll create a variable named affected and call the updatePerson method and pass in the db connection method and the currentPerson object with the new information If the update is successful we ll return a message Let s create the methods we need in person go func getPersonById db sql DB ourID string person rows db Query SELECT id first name last name email ip address FROM people WHERE id ourID defer rows Close ourPerson person for rows Next rows Scan amp ourPerson id amp ourPerson first name amp ourPerson last name amp ourPerson email amp ourPerson ip address return ourPerson This method takes our db object and an ID as a string We run a query to select records that match that ID Then we create a new person object and iterate through the row and scan in each value to the object Once complete we return it After displaying the current values and taking in new ones in main go we need to process the new person object and update the database We ll do that with the updatePerson function func updatePerson db sql DB ourPerson person int stmt err db Prepare UPDATE people set first name last name email ip address where id checkErr err defer stmt Close res err stmt Exec ourPerson first name ourPerson last name ourPerson email ourPerson ip address ourPerson id checkErr err affected err res RowsAffected checkErr err return affected Here we use a prepared statement and use the values from the person object passed in to run an UPDATE against the database We execute the statement and return the rows affected which should be one Save the file and run it Let s fix Lloyd s record Notice the display is all messed up That s because these records contained a newline so it looks funny But we ve updated that record now so they are gone The next time we go to update it we see the newlines are gone And we can now update any record we like and change all the values except for the ID Great Deleting a recordFinally we need to delete a record from the database This is easy in main go let s add the following case option Change case fmt Println Deleting a person by ID tocase reader bufio NewReader os Stdin fmt Print Enter the ID you want to delete searchString reader ReadString n idToDelete strings TrimSuffix searchString n affected deletePerson db idToDelete if affected fmt Println Deleted person from database breakThis will look familiar We re reading in an ID from standard input Then we re trimming the newline and passing that string to a deletePerson method This method takes our db object and the ID we want to delete and returns affected which should be Let s add the deletePerson method to our person go file func deletePerson db sql DB idToDelete string int stmt err db Prepare DELETE FROM people where id checkErr err defer stmt Close res err stmt Exec idToDelete checkErr err affected err res RowsAffected checkErr err return affected The deletePerson method is pretty simple It takes in our db connection and the ID to delete It prepares a statement that s a DELETE and accepts a parameter for id That is inserted into stmt Exec and executed Since there s no output from this command we look for the rows affected and return that as our output Easy Let s delete a record from the database We ll find the id of Lloyd Then we ll build and run our program and enter that ID And now record is gone And now we can successfully Create Read Update and Delete records with our application Exiting the programFinally we need to be able to exit the program Replacecase fmt Println Quitting application withcase fmt Println Goodbye os Exit Now let s build and run it Great Now we have a complete CRUD app with SQLite and Go ConclusionFast small cross platform applications are excellent for many use cases This is why Go is becoming so popular Fast small and self contained databases are the perfect addition to such applications which makes SQLite and Go a natural combination This stack is no silver bullet and won t solve every problem but there are many great uses for this The source code for this demo application is available here If you have any questions or comments let me know If you d like to learn more about Go The Go PlaygroundThe Go Core Language PathTo learn more about SQLite SQLite tutorialsSQLite in Five minutes or less 2022-04-15 21:34:59
海外TECH DEV Community My favorite VS Code extensions https://dev.to/lucamathuse/my-favorite-vs-code-extensions-af2 My favorite VS Code extensions Horizon ThemeLet s kick this off with a beautiful theme shall we The Horizon Theme is the most beautiful theme I ve come across in all my time using Vs Code It s not only easy on the eyes but it also features a very pretty light mode for the ones out there who prefer it to be light Project ManagerProject Manager is great for anyone who has a ton of projects going on at the same time It let s you save any folder as a project in a seperate sidebar you ll find it under the folder looking icon This extension has helped me save a lot of time because I don t have to open my project folders seperately anymore SSH FSThis one s great for anyone who works with remote machines or virtual machines You connect to your device VM with SSH and it show s the entire filesystem or that what your account is allowed to see These were my top three VS Code extensions and my introductory post to this platform Luca 2022-04-15 21:02:56
海外科学 NYT > Science Sidney Altman, Who Stumbled on a Breakthrough in Genetics, Dies at 82 https://www.nytimes.com/2022/04/15/science/sidney-altman-dead.html Sidney Altman Who Stumbled on a Breakthrough in Genetics Dies at He shared a Nobel for finding that RNA was not just a carrier of genetic information but could also trigger life changing chemical reactions in cells 2022-04-15 21:36:57
海外科学 NYT > Science A New Covid Breath Test Holds Promise, but Wide Use May Still Be Far Off https://www.nytimes.com/2022/04/15/health/covid-breath-test-fda.html A New Covid Breath Test Holds Promise but Wide Use May Still Be Far OffThe F D A authorized a breath based test made by a small Texas company which said it hoped that mobile sites could use the device 2022-04-15 21:34:37
海外科学 NYT > Science Biden Plans to Open More Public Land to Drilling https://www.nytimes.com/2022/04/15/climate/biden-drilling-oil-leases.html prices 2022-04-15 21:56:30
海外科学 NYT > Science Why Did the Larsen A and B Ice Shelves Fail? Scientists Say They Now Know. https://www.nytimes.com/2022/04/14/climate/antarctic-ice-shelves-atmospheric-rivers.html Why Did the Larsen A and B Ice Shelves Fail Scientists Say They Now Know The collapse of the two ice shelves was most likely triggered by vast plumes of warm air from the Pacific researchers have found 2022-04-15 21:04:45
ニュース BBC News - Home UK Rwanda asylum plan against international law, says UN refugee agency https://www.bbc.co.uk/news/uk-61122241?at_medium=RSS&at_campaign=KARANGA rwanda 2022-04-15 21:32:39
ニュース BBC News - Home Homes for Ukraine: Robert Jenrick takes in Ukrainian refugee family https://www.bbc.co.uk/news/uk-61122240?at_medium=RSS&at_campaign=KARANGA ukraine 2022-04-15 21:03:56
ニュース BBC News - Home Ukraine war: Grandmother 'horrified' by capture of British fighter https://www.bbc.co.uk/news/uk-61123780?at_medium=RSS&at_campaign=KARANGA russian 2022-04-15 21:21:50
ニュース BBC News - Home Derby County 2-1 Fulham: Rams maintain survival hopes and make Fulham wait on promotion https://www.bbc.co.uk/sport/football/61033751?at_medium=RSS&at_campaign=KARANGA Derby County Fulham Rams maintain survival hopes and make Fulham wait on promotionDerby County come from behind to keep their Championship survival hopes alive and make Fulham wait to secure promotion 2022-04-15 21:10:17
ニュース BBC News - Home Heineken Champions Cup: Bristol 29-35 Sale (agg 39-44) https://www.bbc.co.uk/sport/rugby-union/61107020?at_medium=RSS&at_campaign=KARANGA finals 2022-04-15 21:33:28
北海道 北海道新聞 23年G7サミット、広島が有力 ロシア侵攻で核脅威訴え https://www.hokkaido-np.co.jp/article/670239/ 首脳会議 2022-04-16 06:12:00
北海道 北海道新聞 ミサイル阻止へ攻撃力保有を明記 自民提言案、防衛費GDP2%へ https://www.hokkaido-np.co.jp/article/670238/ 国家安全保障戦略 2022-04-16 06:02:00
ビジネス 東洋経済オンライン ロシアへの経済制裁が期待したほど効かない理由 急落したルーブル相場は「ほぼ元通り」に回復 | 新競馬好きエコノミストの市場深読み劇場 | 東洋経済オンライン https://toyokeizai.net/articles/-/582249?utm_source=rss&utm_medium=http&utm_campaign=link_back 東洋経済オンライン 2022-04-16 06:30:00
ビジネス 東洋経済オンライン 対ロシアで注目、インド「非同盟」の複雑な立場 大国化するインドはこれからどこに向かうのか | ウクライナ侵攻、危機の本質 | 東洋経済オンライン https://toyokeizai.net/articles/-/582217?utm_source=rss&utm_medium=http&utm_campaign=link_back 東洋経済オンライン 2022-04-16 06:30:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)